-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpostfixEvaluation.py
More file actions
29 lines (23 loc) · 1003 Bytes
/
postfixEvaluation.py
File metadata and controls
29 lines (23 loc) · 1003 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
def postfixEvaluation(givenExpression):
digits = [str(x) for x in range(10)]
operations = ['+','-','*','/']
tempStack = []
for i in range(len(givenExpression)):
if givenExpression[i] in digits:
tempStack.append(int(givenExpression[i]))
elif givenExpression[i] in operations:
operand2 = tempStack.pop()
operand1 = tempStack.pop()
if givenExpression[i] == '+':
tempStack.append(operand1 + operand2)
elif givenExpression[i] == '-':
tempStack.append(operand1 - operand2)
elif givenExpression[i] == '*':
tempStack.append(operand1 * operand2)
elif givenExpression[i] == '/':
tempStack.append(operand1 / operand2)
finalAnswer = tempStack.pop()
return finalAnswer
givenExpression = '53+82-*'
print('Given postfix expression was',givenExpression,'and it evaluates to ',end='')
print(postfixEvaluation(givenExpression))