Uber Phone Screen | Solve the Equation with two variables x, y
Anonymous User
442
Dec 20, 2019
Dec 20, 2019
You are give a string representing an equation with 2 variables x and y, value of x is given, solve the value of y.
example:
string = 'x+2y - 3x + 4 = y - 7 + 4x', given x = 3.
There will be only digits, +, -, and =, and no ( ) and * / .
Similar to https://leetcode.com/problems/solve-the-equation/solution/, but I fail to come up with the whole solution in 45 mins. Please comment your ideas down below. Thanks!
Here's a solution I came up with after the interview. It seems not as hard as I thought. Please also comment on this solution!
def solve(s, x):
s = s.replace(" ", "")
s = s.split("=")
leftS = s[0]
rightS = s[1]
leftS = leftS.replace("-", "+-")
rightS = rightS.replace("-", "+-")
leftS = leftS.split("+")
rightS = rightS.split("+")
leftC, leftX, leftY, rightC, rightX, rightY = 0, 0, 0, 0, 0, 0
for subS in leftS:
if "x" in subS:
if subS == "x":
leftX += 1
elif subS == "-x":
leftX -= 1
else:
print(subS[:-1])
leftX += int(subS[:-1])
elif "y" in subS:
if subS == "y":
leftY += 1
elif subS == "-y":
leftY -= 1
else:
leftY += int(subS[:-1])
elif subS:
leftC += int(subS)
for subS in rightS:
if "x" in subS:
if subS == "x":
rightX += 1
elif subS == "-x":
rightX -= 1
else:
rightX += int(subS[:-1])
elif "y" in subS:
if subS == "y":
rightY += 1
elif subS == "-y":
rightY -= 1
else:
rightY += int(subS[:-1])
elif subS:
rightC += int(subS)
leftY -= rightY
rightX -= leftX
rightC -= leftC
if x == 0:
if leftY != 0:
return "y = " + str(rightC / leftY)
else:
return "y could be any value"
else:
if leftY != 0:
return "y = " + str((rightX * x + rightC) / leftY)
elif rightX * x + rightC != 0:
return "No solution"
else:
return "y could be any value"
s = "x + y + 1 = 10 + 2x + 2y"
print(solve(s, 4))
Comments (2)


