infix to postfix python code

Solutions on MaxInterview for infix to postfix python code by the best coders in the world

showing results for - "infix to postfix python code"
Martina
03 Jan 2020
1class stack:
2def __init__(self):
3    self.item = []
4
5def push(self,it):
6    self.item.append(it)
7def peek(self):
8    if self.isempty() == True:
9        return 0
10    return self.item[-1]
11
12def pop(self):
13    if self.isempty() == True:
14        return 0
15    return(self.item.pop())
16
17def length(self):
18    return (len(self.item))
19
20
21def isempty(self):
22    if self.item == []:
23        return True
24    else:
25        return False
26
27def display(self):
28    if self.isempty()== True:
29        return
30    temps = stack()
31    while(self.isempty() != True):
32        x = self.peek()
33        print("~",x)
34        temps.push(x)
35        self.pop()
36    while(temps.isempty() != True):
37        x = temps.peek()
38        self.push(x)
39        temps.pop()
40
41
42def isOperand(self, ch): 
43    return ch.isalpha()
44def notGreater(self, i):
45    precedence = {'+':1, '-':1, '*':2, '/':2, '%':2, '^':3}
46    if self.peek() == '(':
47        return False
48    a = precedence[i]
49    b = precedence[self.peek()] 
50    if a  <= b:
51        return True
52    else:
53        return False
54        
55
56
57def infixToPostfix(self, exp):
58    output = ""
59    
60    for i in exp:
61        
62        if self.isOperand(i) == True: # check if operand add to output
63            print(i,"~ Operand push to stack")
64            output = output + i
65
66        # If the character is an '(', push it to stack 
67        elif i  == '(':
68            self.push(i)
69            print(i," ~ Found ( push into stack")
70
71        elif i == ')':  # if ')' pop till '('
72            while( self.isempty() != True and self.peek() != '('):
73                n = self.pop() 
74                output = output + n
75                print(n, "~ Operator popped from stack")
76            if (self.isempty() != True and self.peek() != '('):
77                print("_________")
78                return -1
79            else:
80                x = self.pop()
81                print(x, "Popping and deleting (")
82        else: 
83            while(self.isempty() != True and self.notGreater(i)):
84                c = self.pop()
85                output = output + c
86                print(c,"Operator popped after checking precedence from stack")
87            self.push(i)
88            print(i,"Operator pushed to stack")
89
90    # pop all the operator from the stack 
91    while self.isempty() != True:
92        xx = self.pop()
93        output = output + xx
94        print(xx,"~ pop at last")
95    print(output)
96    self.display()
97st = stack()
98st.infixToPostfix("a+(b*c)")
99