forked from prakhar1989/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack-adt.py
More file actions
74 lines (63 loc) · 2.08 KB
/
Copy pathstack-adt.py
File metadata and controls
74 lines (63 loc) · 2.08 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Stack(object):
""" A simple stack ADT with top as the end of a list """
def __init__(self):
self.items = []
def __str__(self):
return ("Stack of size: %d" % len(self.items))
def isEmpty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def top(self):
if self.isEmpty(): return None
return self.items[len(self.items)-1]
def string_reverse(s):
stack = Stack()
rev = []
for c in s: stack.push(c)
while not stack.isEmpty():
rev.append(stack.pop())
return "".join(rev)
def match_paren(parens):
""" returns true or false if parenthesis
expression passed is matching"""
stack = Stack()
for b in parens:
if b == "(":
stack.push(1)
else: # b == ")"
if not stack.isEmpty():
stack.pop()
else:
return False
return stack.isEmpty()
def infix_to_postfix(infixexpr):
prec = { '+': 2, '-': 2, '*': 3, '/': 3,'(': 1 } # denoting precedence
operator_stack = Stack()
operators = "+-*/()"
output_list = []
for token in infixexpr.split():
if token not in operators:
output_list.append(token)
elif token == "(":
operator_stack.push("(")
elif token == ")":
topToken = operator_stack.pop()
while topToken != "(":
output_list.append(topToken)
topToken = operator_stack.pop()
else: # an operator
while (not operator_stack.isEmpty()) and \
(prec[operator_stack.top()] >= prec[token]):
output_list.append(operator_stack.pop())
operator_stack.push(token)
# tokens exhausted - empty out the stack
while not operator_stack.isEmpty():
output_list.append(operator_stack.pop())
return " ".join(output_list)
if __name__ == "__main__":
expr = ["A * B + C * D", "( A + B ) * C - ( D - E ) * ( F + G )"]
for e in expr:
print infix_to_postfix(e)