给你一个string和x的value让你解出y的值
比如'2x - ((x - (3x + 1) + 2) + 3) + 4 = x + y'
def caculate(s, xVal):
l, r = s.split('=')
lNumX, lNumY, lNum = processOneSide(l, 1)
rNumX, rNumY, rNum = processOneSide(r, -1)
x = (lNumX + rNumX)*xVal
yDigit = lNumY + rNumY
return (-x-(lNum+rNum))/float(yDigit)
def processOneSide(s, globalSign):
numX = 0
numY = 0
num = 0
tmpNum = 0
sign = 1
stack = []
cur_sign = 1
for i, c in enumerate(s):
if c.isdigit():
tmpNum = tmpNum*10 + int(c)
elif c=='x':
if not tmpNum:
numX += 1*sign*cur_sign
else:
numX += tmpNum*sign*cur_sign
tmpNum = 0
elif c=='y':
if not tmpNum:
numY += 1*sign*cur_sign
else:
numY += tmpNum*sign*cur_sign
tmpNum = 0
elif c in '+-':
num += tmpNum*sign*cur_sign
sign = [-1, 1][c=='+']
tmpNum = 0
elif c in '(':
stack.append(sign)
cur_sign *= sign
sign = 1
elif c in ')':
if i == len(s)-1:
num += tmpNum*sign*cur_sign
tmpNum = 0
cur_sign *= stack.pop()
sign = 1
if tmpNum != 0:
print (sign, cur_sign)
num += tmpNum*sign*cur_sign
return (globalSign*numX, globalSign*numY, globalSign*num)
# s = '2x - (4x+ y) = 1'
# print caculate(s, 1)
s = '2x - ((x - (3x + 1) + 2) + 3) + 4 = x + y'
1 - 2 - 3 + 4
print caculate(s, 1)