Skip to content

Commit 71c8e8e

Browse files
authored
Create solve-the-equation.py
1 parent a7cbffc commit 71c8e8e

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Python/solve-the-equation.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# Solve a given equation and return the value of x in the form of string "x=#value".
5+
# The equation contains only '+', '-' operation, the variable x and its coefficient.
6+
#
7+
# If there is no solution for the equation, return "No solution".
8+
#
9+
# If there are infinite solutions for the equation, return "Infinite solutions".
10+
#
11+
# If there is exactly one solution for the equation, we ensure that the value of x is an integer.
12+
#
13+
# Example 1:
14+
# Input: "x+5-3+x=6+x-2"
15+
# Output: "x=2"
16+
# Example 2:
17+
# Input: "x=x"
18+
# Output: "Infinite solutions"
19+
# Example 3:
20+
# Input: "2x=x"
21+
# Output: "x=0"
22+
# Example 4:
23+
# Input: "2x+3x-6x=x+2"
24+
# Output: "x=-1"
25+
# Example 5:
26+
# Input: "x=x+2"
27+
# Output: "No solution"
28+
29+
class Solution(object):
30+
def solveEquation(self, equation):
31+
"""
32+
:type equation: str
33+
:rtype: str
34+
"""
35+
a, b = 0, 0
36+
side = 1
37+
for eq, sign, num, isx in re.findall('(=)|([-+]?)(\d*)(x?)', equation):
38+
if eq:
39+
side = -1
40+
elif isx:
41+
a += side * int(sign + '1') * int(num or 1)
42+
elif num:
43+
b -= side * int(sign + num)
44+
return 'x=%d' % (b / a) if a else 'No solution' if b else 'Infinite solutions'

0 commit comments

Comments
 (0)