forked from mattbatwings/3D-Graphing-Calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.py
More file actions
55 lines (40 loc) · 1.31 KB
/
parse.py
File metadata and controls
55 lines (40 loc) · 1.31 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
# A simulator for the redstone parser - the first part of the graphing calculator.
# Converts a list of characters (0-9,x,y,z,+,-) to a list of terms (sign, coefficient, x degree, y degree, z degree).
def parse_polynomial(poly):
terms = []
# Term state
sign = 0
coef = 0
x_deg = y_deg = z_deg = 0
# Helper state
coef_seen = False
def commit_term():
nonlocal sign, coef, coef_seen, x_deg, y_deg, z_deg
terms.append([sign, coef if coef_seen else 1, x_deg, y_deg, z_deg])
sign = 0
coef = 0
coef_seen = False
x_deg = y_deg = z_deg = 0
for char in poly:
# Term separator
if char == '+' or char == '-':
commit_term()
sign = 1 if char == '-' else 0
# Digit (coefficient or exponent)
elif '0' <= char <= '9':
coef = coef * 10 + int(char)
coef_seen = True
# Variable
elif char in 'xyz':
if char == 'x':
x_deg += 1
elif char == 'y':
y_deg += 1
elif char == 'z':
z_deg += 1
# Commit final term
commit_term()
return terms
# Example
poly = "3xyzzz-4xyyz-7yxz"
print(parse_polynomial(poly))