-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalc.py
84 lines (74 loc) · 2.45 KB
/
calc.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3
import re
# Helper function that returns true if the given string is
# a valid operator.
#
# This has been implemented for you, you don't need to
# modify it.
def is_operator(token: str) -> bool:
return re.search("^[\\+\\-\\/\\*\\^]$", token) != None
# Helper function that returns true if the given string is
# a valid operand.
#
# This has been implemented for you, you don't need to
# modify it.
def is_operand(token: str) -> bool:
return re.search("^[0-9]+$", token) != None
# Helper function that returns the result of the operation
# requested.
#
# This has been implemented for you, you don't need to
# modify it.
#
# Returns [op1] [operand] [op2]
def apply_operation(op1: float, op2: float, operand: str) -> float:
if not isinstance(op1, float):
raise ValueError(f"Expected first operand of type float, got {type(op1)}")
if not isinstance(op2, float):
raise ValueError(f"Expected second operand of type float, got {type(op2)}")
if not isinstance(operand, str) or len(operand) != 1:
raise ValueError(f"Expected operator of type string and len 1, got {type(operand)} or len {len(operand)}: \"{operand}\"")
if operand == "+":
return op1 + op2
elif operand == "-":
return op1 - op2
elif operand == "*":
return op1 * op2
elif operand == "/":
return op1 / op2
else:
raise ValueError(f"Illegal operand {operand}")
# Takes a list of tokens produced by `tokenize_expression`
# and evaluates them to produce a result. Returns that
# result.
#
# See README.md for resources about how this can be
# implemented.
def evaluate_tokens(tokens: list) -> float:
pass
# Takes an expression stored in `expr` and returns a
# list containing each token in that expression.
#
# Example:
# INPUT: "+ 1 * 4 / 7 + 1 3"
# OUTPUT: ["+", "1", "*", "4", "/", "7", "+", "1", "3"]
def tokenize_expression(expr: str) -> list:
pass
# This is the main function that does the input/output
# from the user and calls the functions you implemented
# above.
#
# This has been implemented for you, you don't need to
# modify it.
def main():
while True:
try:
expr = input("Enter expression to be evaluated (or Ctrl + D to exit)\n> ")
tokens = tokenize_expression(expr)
result = evaluate_tokens(tokens)
print(result);
except EOFError:
print()
exit(0)
if __name__ == "__main__":
main()