-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostfix_to_infix_conversion.py
59 lines (42 loc) · 1.34 KB
/
postfix_to_infix_conversion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
You are given a string that represents the postfix form of a valid mathematical expression. Convert it to its infix form.
Example:
Input:
ab*c+
Output:
((a*b)+c)
Explanation:
The above output is its valid infix form.
Your Task:
Complete the function string postToInfix(string post_exp), which takes a postfix string as input and returns its infix form.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
3<=post_exp.length()<=104
"""
class Solution:
def isOperand(self,x):
return ((x >= 'a' and x <= 'z') or
(x >= 'A' and x <= 'Z'))
# Get Infix for a given postfix
# expression
def postToInfix(self, postfix):
s = []
for i in postfix:
# Push operands
if (self.isOperand(i)) :
s.insert(0, i)
# We assume that input is a
# valid postfix and expect
# an operator.
else:
op1 = s[0]
s.pop(0)
op2 = s[0]
s.pop(0)
s.insert(0, "(" + op2 + i +
op1 + ")")
# There must be a single element in
# stack now which is the required
# infix.
return s[0]