[英]How do you use a string to solve a math equation using python?
我正在尝试制作一个python程序,它接受一个用户等式,例如:“ 168/24+8=11*3-16
”,并试图通过删除任何2来使等式的两边相等用户输入的字符。 这是我到目前为止:
def compute(side):
val = int(side[0])
x= val
y=0
z=None
for i in range(1, len(side)-1):
if side[i].isdigit():
x= (x*10)+ int(side[i])
if x == side[i].isdigit():
x= int(side[i])
else:
op = side[i]
if op=="+":
val += x
elif op == "-":
val -= x
elif op == "*":
val *= x
else:
val /= x
return print(val)
我编辑了我的计算功能。
def evaluate(e):
side1 = ""
side2 = ""
equalsign = e.index("=")
side1= e[:equalsign - 1]
side2= e[:equalsign + 1]
if compute (side1) == compute(side2):
return True
else:
return False
def solve():
# use a for loop with in a for loop to compare all possible pairs
pass
def main():
e= input("Enter an equation: ")
evaluate(e)
main()
对于实际的solve
函数,我想测试方程每一侧的所有可能的对,并且每一对都被移除,检查方程是否等于另一侧。 我在考虑使用for
循环说:
for i in side1:
j= [:x]+[x+1:y]+[y+1:]
if compute(j)==compute(side2):
val= compute(j)
return val
我该怎么做呢? 我对如何真正接近这个程序感到有些困惑。
让我们来看看初步问题。
e = raw_input("Enter an equation: ") # input is fine if you are using Python3.x
side1 = e[:equalsign] #note that a[start:end] does not include a[end]
side2 = e[equalsign + 1:] # not e[:equalsign + 1]
。
val = int(side[0]) # not val = side[0] which will make val a string
在操作部分,你正在做val += side # or -= / *= / /= .. remember side is a string
编辑:
input
) eval(side1) # or eval(side2)
。 可能有使用eval
替代方案。 (我自己是新手)。 eval
还将负责PEMDAS。 side1
表达式的编辑。 更新了目前为止编写的代码。
def compute(side): return eval(side) def evaluate(e): side1, side2 = e.split('=') if compute(side1) == compute(side2): return (True, e) else: return (False, 'Not Possible') def solve(e): for i in range(len(e)): # loop through user input if e[i] in '=': # you dont want to remove the equal sign continue for j in range(i+1, len(e)): # loop from the next index, you dont want if e[j] in '=': # to remove the same char continue # you dont want to remove '=' or operators new_exp = e[:i] + e[i+1:j] + e[j+1:] # e[i] and e[j] are the removed chars #print e[i], e[j], new_exp # this is the new expression s1, s2 = new_exp.split('=') try: if compute(s1) == compute(s2): return (True, new_exp) except: continue return (False, 'not possible') def main(): e= raw_input("Enter an equation: ") print evaluate(e.replace(' ', '')) main()
这是我到目前为止所提出的(至少适用于你的例子)。
最终编辑:考虑到@Chronical的建议更新了代码
try-except
块,而不是在计算每一侧后使用它 这是完全符合您要求的代码:
from itertools import combinations
def calc(term):
try:
return eval(term)
except SyntaxError:
return None
def check(e):
sides = e.split("=")
if len(sides) != 2:
return False
return calc(sides[0]) == calc(sides[1])
equation = "168/24+8 = 11*3-16".replace(" ", "")
for (a, b) in combinations(range(len(equation)), 2):
equ = equation[:a] + equation[a+1:b] + equation[b+1:]
if check(equ):
print equ
核心技巧:
eval()
进行评估。 如果您将此用于任何事情,请注意此技巧的安全隐患。 itertools.combinations
创建要删除的所有可能的字符对 =
太特别 - 只需在check()
捕获它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.