-
Notifications
You must be signed in to change notification settings - Fork 0
/
Algebra.py
53 lines (52 loc) · 1.72 KB
/
Algebra.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
#Benjamin Maymir
#maymi001@umn.edu
def left(e):return e[0]
def op(e):return e[1]
def right(e):return e[2]
def isInside(v,e):
if(len(e)==1):
return e==v
else:
return isInside(v,left(e)) or isInside(v,right(e))
def solve(v,q):
if(isInside(v,left(q))):
return(solving(v,q))
elif(isInside(v,right(q))):
return(solving(v,(right(q),'=',left(q))))
else:
raise ValueError("Variable not found in equation")
def solving(v,q):
if(v==left(q)):
return q
else:
if(op(left(q))=='+'):
return solving(v,solvingAdd(v,q))
elif(op(left(q))=='-'):
return solving(v,solvingSubtract(v,q))
elif(op(left(q))=='*'):
return solving(v,solvingMultiply(v,q))
elif(op(left(q))=='/'):
return solving(v,solvingDivide(v,q))
else:
raise ValueError('Operation '+op(left(q))+" is not defined")
def solvingAdd(v,q):
if(isInside(v,left(left(q)))):
return(left(left(q)),'=',(right(q),'-',right(left(q))))
else:
return(right(left(q)),'=',(right(q),'-',left(left(q))))
def solvingSubtract(v,q):
if(isInside(v,left(left(q)))):
return(left(left(q)),'=',(right(q),'+',right(left(q))))
else:
return(right(left(q)),'=',(left(left(q)),'-',right(q)))
def solvingMultiply(v,q):
if(isInside(v,left(left(q)))):
return(left(left(q)),'=',(right(q),'/',right(left(q))))
else:
return(right(left(q)),'=',(right(q),'/',left(left(q))))
def solvingDivide(v,q):
if(isInside(v,left(left(q)))):
return(left(left(q)),'=',(right(q),'*',right(left(q))))
else:
return(right(left(q)),'=',(left(left(q)),'/',right(q)))
solving('x',(('x','%','4'),'=','2'))