-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
66 lines (52 loc) · 1.67 KB
/
main.py
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
import sys
import argparse
import readline # noqa: F401, brings in up-arrow history
# local imports
import rpn_calc
import menu
def interactive_mode():
error_counter = 0
while True:
try:
try:
expression = input(" > ")
except KeyboardInterrupt:
exit(0)
expression = expression.strip().split()
result = rpn_calc.evaluate_rpn(expression)
if result is None:
error_counter += 1
if error_counter > 5:
menu.ask_for_help()
error_counter = 0
print_stack = " ".join(
str(int(x)) if isinstance(x, float) and x.is_integer() else str(x)
for x in rpn_calc.stack
)
print(f"{print_stack}", end="")
except EOFError:
exit(0)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("expression", nargs="*")
args = parser.parse_args()
if not sys.stdin.isatty():
expression = sys.stdin.read().strip().split()
elif args.expression:
expression = args.expression
else:
interactive_mode()
return
result = rpn_calc.evaluate_rpn(expression)
if result is not None:
if len(rpn_calc.stack) > 1:
print("Incomplete expression, remaining stack: ", end='')
print_stack = " ".join(
str(int(x)) if isinstance(x, float) and x.is_integer() else str(x)
for x in rpn_calc.stack
)
print(f"{print_stack}")
else:
print("Expression did not evaluate. Try 'rpn help' for more info")
if __name__ == "__main__":
main()