-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEquationSolve.py
143 lines (123 loc) · 3.94 KB
/
EquationSolve.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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
class EquationSolver:
"""This class solves a linear equation with a single unknown variable and prints the value.
Args:
data(object): The JSON object.
"""
def __init__(self, data):
self.data = data
def convertToInfix(self,prefix):
"""This function converts a prefix expression to an infix expression
Args:
prefix(list): The Prefix expression as a list.
Returns:
list: The resultant infix expression.
"""
prefix.reverse()
stack = []
result = ""
for i in prefix:
if(type(i) is int):
stack.append(i)
elif(i == "x"):
stack.append(i)
else:
one = stack[-1]
stack.pop()
two = stack[-1]
stack.pop()
if(type(one) is int and type(two) is int):
temp = str(one) + i + str(two)
stack.append(int(eval(temp)))
else:
result = "( " + str(two) + " " + str(i) + " " + str(one) + " )"
stack.append(result)
result = stack[-1]
return map(str,result.split())
def getEquationInRight(self,infix,rhs):
"""This function shifts all operators and operands excluding x to the right hand side (rhs)
Args:
infix(list): The infix expression as a list.
rhs(int): The initial value of the rhs provided in the JSON File
Variables:
dictionary(dict): Stores the complement of the operators when shifted.
Returns:
str: The required solution in the form x = ____
"""
stack = []
infix.reverse()
stack.append(rhs)
dictionary = {
"/" : "*" , "*" : "/",
"-" : "+" , "=" : "=",
"+" : "-"
}
result = ""
for i in infix:
if (type(i) is str):
if (i == "(" or i == ")"):
continue
if (i == "x"):
break
if (i=="*" or i=="/" or i=="+" or i=="-"):
result = "( " + str(stack[-2]) + " " + dictionary[str(i)] + " " + str(stack[-1]) + " )"
stack.pop()
stack.pop()
stack.append(result)
else:
stack.append(int(i))
infix.reverse()
for i in infix:
if (type(i) is str):
if (i == "(" or i == ")"):
continue
if (i == "x"):
break
if (i == "*" or i == "/" or i == "+" or i == "-"):
result = "( " + str(stack[-2]) + " " + dictionary[ str(i) ] + " " + str(stack[-1]) + " )"
stack.pop()
stack.pop()
stack.append(result)
else:
stack.append(int(i))
return stack[0]
def convertToPrefix(self,data):
"""This function recursively converts the given JSON object into an expression tree with pre-prder traversal resulting in a prefix expression.
Args:
data(object): The JSON Object.
Variables:
dictionary(dict): Stores the equivalent unicode of the operators.
Returns:
list: The prefix form of the expression.
"""
prefix = []
dictionary = {
"multiply" : "*" , "divide" : "/",
"add" : "+" , "equal" : "=",
"subtract" : "-" , "x" : "x"
}
for i in data.items():
if (type(i[1]) is dict):
prefix.extend(self.convertToPrefix(i[1]))
if type(i[1]) is int:
prefix.append( i[1] )
elif type(i[1]) is unicode:
prefix.append(dictionary[i[1]])
return prefix
def solve(self, data):
"""This function calls the required functions sequentially to solve the problem.
First the prefix expression is extracted.
Then the '=' operand is removed and the initial rhs value is saved and removed from the prefix expression.
Then the prefix is converted into infix and then shifted to the right and finally evaluated.
Total Time Complexity: O(n) (Linear)
Args:
data(object): The JSON Object
"""
prefixExp = self.convertToPrefix(self.data)
prefixExp.pop() #Pop the operand =
rhs = int(prefixExp[0])
prefixExp.reverse()
prefixExp.pop() #Pop the initial value of RHS
infix = self.convertToInfix(prefixExp)
rhsValue = self.getEquationInRight(infix,rhs)
print "x =", rhsValue
print "x =", eval(rhsValue)