-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinearsolver
More file actions
executable file
·75 lines (49 loc) · 1.65 KB
/
Copy pathlinearsolver
File metadata and controls
executable file
·75 lines (49 loc) · 1.65 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
#!/usr/bin/env python3
import re
import sys
from sympy import symbols, Eq, solve, sympify
PRECISION = 2
def is_expression(arg):
return bool(re.match(r".*=-?(\d+(\.\d+)?)$", arg))
def get_constant(expr):
return re.search(r"(?<==).*", expr).group().strip()
def get_equation(expr):
eq = re.search(r"^.*(?==)", expr).group().strip()
return re.sub(r'(\d+)([a-zA-Z]+\d*)', r'\1*\2', eq)
def get_symbols(args):
variables = set()
for arg in args:
vrs = re.findall(r"([a-zA-Z]+\d*)", arg)
variables.update(vrs)
return list(variables)
def argument_error(args):
print("Use:", args[0], "<option> <expr 1> ... <expr N>")
exit(1)
def main():
fractions = False
if len(sys.argv) < 2:
argument_error(sys.argv)
if not is_expression(sys.argv[1]):
if sys.argv[1] != "-f":
argument_error(sys.argv)
fractions = True
sys.argv.pop(1)
syms = get_symbols(sys.argv[1:])
variables = symbols(syms)
equations = []
for expr in sys.argv[1:]:
if not is_expression(expr):
argument_error(sys.argv)
lhs = sympify(get_equation(expr))
rhs = sympify(get_constant(expr))
equations.append(Eq(lhs, rhs))
sol = solve(equations, variables)
if not sol:
print("No solution.")
elif fractions or len(variables) != len(sys.argv) - 1:
print(", ".join(f"{var} = {val}" for var, val in sol.items()))
else:
sdec = {var: round(float(val.evalf()), PRECISION) for var, val in sol.items()}
print(", ".join(f"{var} = {val}" for var, val in sdec.items()))
if __name__== "__main__":
main()