-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScript64_Project_08_Postfix_Evaluation_Function_Part1.py
More file actions
87 lines (68 loc) · 2.14 KB
/
Script64_Project_08_Postfix_Evaluation_Function_Part1.py
File metadata and controls
87 lines (68 loc) · 2.14 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
75
76
77
78
79
80
81
82
83
84
85
86
87
# In the name of God
# Mohammad Hossein Zehtab
# python-evens-17
# Project 08: Postfix Evaluation Function Part 1
import re
class Stack:
'''
Creates a new stack.
'''
def __init__(self):
'''
Creates a new stack using python list class.
'''
self.items = []
def push(self, item):
'''
Append a new item in the stack.
'''
self.items.append(item)
def pop(self):
'''
Pop and return the last item on the top of the stack.
'''
return self.items.pop()
def is_empty(self):
'''
Check that stack is empty or not.
'''
return (self.items == [])
def __str__(self):
return f'{self.items}'
def eval_postfix(exp):
'''
Evaluates a postfix expresion
'''
token_list = re.split('([^0-9])', exp)
stack = Stack()
for token in token_list:
if token == '' or token == ' ': continue
elif token == '+':
summ = stack.pop() + stack.pop()
stack.push(summ)
elif token == '*':
prod = stack.pop() * stack.pop()
stack.push(prod)
elif token == '/':
denominator = stack.pop()
numerator = stack.pop()
div = numerator / denominator
stack.push(div)
elif token == '-':
subtrahend = stack.pop()
minuhend = stack.pop()
sub = minuhend - subtrahend
stack.push(sub)
else:
stack.push(int(token))
# print(stack) Debugging
return stack.pop()
### Driver Code ###
print(eval_postfix("56 47 + 2 *"))
print(eval_postfix("1 2 + 3 *"))
print(eval_postfix("2 6 3 / 4 -*"))
# =============================================================================
# print(eval_postfix("5647+2*"))
# print(eval_postfix("12+3 *"))
# print(eval_postfix("263/4-*"))
# =============================================================================