-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSymbolics.py
More file actions
66 lines (62 loc) · 2.67 KB
/
Symbolics.py
File metadata and controls
66 lines (62 loc) · 2.67 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
OPERATORS = ["**", "*", "//", "/", "%", "+", "-"]
BASIC = "%()*+-./0123456789"
ENGLISH = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
GREEK = "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψω"
VALID = BASIC + ENGLISH + GREEK
def parse_expr(expr: str) -> list:
expr = expr.replace(" ", "")
if any([item not in VALID for item in expr]):
raise ValueError("Characters other than Arabic numerals, English letters, Greek letters, operators, "
"decimal points, and parentheses cannot appear in expressions")
depth = 0
pointer = 0
result = []
for index in range(len(expr)):
if expr[index] == "(":
if depth == 0:
result.append(index)
depth += 1
elif expr[index] == ")":
if depth == 0:
raise ValueError("The parentheses in the expression are not paired")
depth -= 1
if depth == 0:
sub = parse_expr(expr[result[-1] + 1:index])
if not sub:
raise ValueError("The inside of the parentheses in an expression cannot be empty")
result[-1] = sub
elif depth == 0 and expr[index] in OPERATORS:
number = expr[pointer:index]
if number and "(" not in number:
if number.count(".") > 1:
raise ValueError("Syntax error in expression")
nan = True
for item in number:
if nan and item.isdigit():
nan = False
elif not nan and not (item == "." or item.isdigit()):
raise NameError("The name of the algebra is invalid")
result.append(number)
if index != 0:
pointer = index + 1
else:
pointer = index
if expr[index] in "*/" and expr[index] == expr[index - 1]:
if result[-1] in OPERATORS:
raise ValueError("Syntax error in expression")
result.append(expr[index] * 2)
elif index != 0 and expr[index] != expr[index + 1]:
if result[-1] in OPERATORS:
raise ValueError("Syntax error in expression")
result.append(expr[index])
number = expr[pointer:]
if number and "(" not in number:
result.append(number)
if depth != 0:
raise ValueError("The parentheses in the expression are not paired")
return result
# TODO 表达式展开
# TODO 表达式化简
# TODO 符号微分
# TODO 符号积分
...