forked from souravjain540/Basic-Python-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfixeval.py
More file actions
32 lines (27 loc) · 720 Bytes
/
postfixeval.py
File metadata and controls
32 lines (27 loc) · 720 Bytes
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
class Stack:
def __init__(self):
self.stack = []
def push(self, val):
self.stack.append(val)
def pop_(self):
if not self.stack:
return
else:
return self.stack.pop()
def posteval(expression):
stk = Stack()
for i in expression:
if i.isdigit():
stk.push(i)
else:
a = int(stk.pop_())
b = int(stk.pop_())
if i == '^':
temp = f'{b}**{a}'
stk.push(str(eval(temp)))
else:
temp = f'{b}{i}{a}'
stk.push(eval(temp))
return stk.stack[0]
postfix = input("Enter postfix expression: ")
print(posteval(postfix))