-
Notifications
You must be signed in to change notification settings - Fork 88
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added program for Infix to Postfix in Python
- Loading branch information
1 parent
6bb9ff5
commit 521e770
Showing
1 changed file
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |