提问人:Nekomane 提问时间:9/13/2023 最后编辑:Nekomane 更新时间:9/13/2023 访问量:20
求解字符串时 Eval 函数不起作用
Eval function not working when solving for a string
问:
我正在创建一个数学计算器,它使用字符串拼接将变量替换为各自的值。一旦我用变量代替了等式的两边,每当尝试计算表达式时,我都会收到一个错误。(给定代码中的值,它应该打印 26。( 35 - 3(3) = 26 )
def apply_x(x, LHS):
for i in range(len(LHS.strip())):
if LHS[i] == 'x':
output = LHS[0:i] + '(' + x + ')' + LHS[i+1:len(LHS)]
for i in range(len(output.strip())):
if output[i] == 'x':
output = output[0:i] + '(' + x + ')' + output[i+1:len(output)]
return str(output)
equation = '35 - 3x = -8x - 5(5 - 5x)'
index = equation.find('=')
LHS = equation[0:index] # Left Hand Side
RHS = equation[index + 1:len(equation)] # Right Hand Side
x = 3
LHS_int = apply_x(str(x), LHS)
RHS_int = apply_x(str(x), RHS)
print('Original: '+equation)
print('Subbed: ' + LHS_int + '=' + RHS_int)
print('\nLHS Original: ' + str(LHS.strip()))
print('LHS Subbed : ' + LHS_int.strip())
print('RHS Original: ' + str(RHS.strip()))
print('RHS Subbed: ' + RHS_int.strip())
'''
I want the code to solve each side and check to see if
The Equation is true/false .
'''
答: 暂无答案
评论
3(3)