-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfixcalc.py
More file actions
80 lines (66 loc) · 1.35 KB
/
postfixcalc.py
File metadata and controls
80 lines (66 loc) · 1.35 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
import sys
pol = str(sys.argv[1])
pol = pol.split(" ")
def create_stack():
stack = []
return stack
def push(stack, item):
stack.append(item)
def pop(stack):
if is_empty(stack):
return "error"
else:
return stack.pop()
def top(stack):
if is_empty(stack):
return "error"
else:
return stack[-1]
def is_empty(stack):
return len(stack) == 0
oprtns = ["+","-","/","*"]
def calc(x, y, op):
if op == "+":
return x + y
elif op == "-":
return x - y
elif op == "*":
return x*y
elif op == "/":
return x/y
stack = create_stack()
flag = 0
try:
for x in pol:
if x in oprtns:
if not is_empty(stack):
b = pop(stack)
if not is_empty(stack):
a = pop(stack)
push(stack, calc(a, b, x))
else:
print("invalid input")
flag = 1
break
else:
print("invalid input")
flag = 1
break
else:
push(stack, int(x))
if len(stack) == 1:
print(stack[0])
elif len(stack) != 1 and not flag:
print("invalid input")
flag = 1
except ValueError:
if flag == 0:
print("invalid input")
flag = 1
except IndexError:
if flag == 0:
print("invalid input")
#python3 postfixcalc.py "4 3 2 * +"
#python3 postfixcalc.py "3 9 + 2 / 5 * 15 10 - 5 / -"
#python3 postfixcalc.py "3 9 + +"
#python3 postfixcalc.py "3 9 5 - +"