-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
93 lines (68 loc) · 2.2 KB
/
Copy pathmain.py
File metadata and controls
93 lines (68 loc) · 2.2 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
81
82
83
84
85
86
87
88
89
90
91
92
93
import sys
import math
import re
text = input(": ")
text = text.replace(" ", "")
# print("Equation without spaces: " + text)
def is_number(value):
return value.isnumeric()
def is_operator(value):
return value in ["+", "-", "*", "/", "^"]
def parse_equation(equation):
temp_number = ""
items = []
for char in equation:
if is_number(char):
temp_number += char
else:
if temp_number:
items.append({
"value": temp_number,
"type": "number"
})
temp_number = ""
if is_operator(char):
items.append({
"value": char,
"type": "operator"
})
if temp_number:
items.append({
"value": temp_number,
"type": "number"
})
return items
parsed_equation = parse_equation(text)
if len(parsed_equation) == 0:
raise SyntaxError("INVALID SYNTAX: NO NUMBERS OR OPERATIONS")
print("Parsed equation: " + str(parsed_equation))
# Checks
if parsed_equation[0]["type"] == "operator":
raise SyntaxError("INVALID SYNTAX: MISPLACED OPERATOR")
def solve_equation(equation):
value = equation[0]["value"]
equation.pop(0)
operating_next_value = False
next_operator = ""
for x in equation:
type_ = x["type"]
if operating_next_value:
if type_ == "operator":
raise SyntaxError("INVALID SYNTAX: MISPLACED OPERATOR")
if next_operator == "+":
value = int(value) + int(x["value"])
elif next_operator == "-":
value = int(value) - int(x["value"])
elif next_operator == "*":
value = int(value) * int(x["value"])
elif next_operator == "/":
value = int(value) / int(x["value"])
elif next_operator == "^":
value = int(value) ** int(x["value"])
next_operator = ""
operating_next_value = False
if type_ == "operator":
operating_next_value = True
next_operator = x["value"]
return value
print(str(solve_equation(parsed_equation)))