Skip to content

Commit

Permalink
Infix to postfix in Python
Browse files Browse the repository at this point in the history
Added program for Infix to Postfix in Python
  • Loading branch information
bratinkundu authored Oct 4, 2020
1 parent 6bb9ff5 commit 521e770
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions Python/InfixToPostfix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@

class SampleProgram :

def __init__(self, capacity):
self.top = -1
self.capacity = capacity
self.array = []
self.output = []
self.precedence = {'+':1, '-':1, '*':2, '/':2, '^':3}

def isEmpty(self):
return True if self.top == -1 else False

def peek(self):
return self.array[-1]

def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"

def push(self, op):
self.top += 1
self.array.append(op)

def isOperand(self, ch):
return ch.isalpha()

def notGreater(self, i):
try:
a = self.precedence[i]
b = self.precedence[self.peek()]
return True if a <= b else False
except KeyError:
return False


def InfixToPostfix(self, exp):

for i in exp:
if self.isOperand(i):
self.output.append(i)

elif i == '(':
self.push(i)

elif i == ')':
while( (not self.isEmpty()) and self.peek() != '('):
a = self.pop()
self.output.append(a)
if (not self.isEmpty() and self.peek() != '('):
return -1
else:
self.pop()

else:
while(not self.isEmpty() and self.notGreater(i)):
self.output.append(self.pop())
self.push(i)

while not self.isEmpty():
self.output.append(self.pop())

print "".join(self.output)

exp = "a+b*(c^d-e)^(f+g*h)-i"
obj = SampleProgram(len(exp))
obj.InfixToPostfix(exp)

0 comments on commit 521e770

Please sign in to comment.