如何使用字符串使用python解数学方程?
我正在尝试制作一个python程序,它接受一个用户等式,例如:“如何使用字符串使用python解数学方程?,python,string-parsing,python-3.4,Python,String Parsing,Python 3.4,我正在尝试制作一个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=
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(“输入公式:”)#如果您使用的是Python3.x,那么输入就可以了
side1=e[:equalsign]#请注意,[start:end]不包括[end]
side2=e[equalsign+1:]#不是e[:equalsign+1]
val=int(side[0])#而不是val=side[0],这将使val成为字符串
- 在操作部分,您正在执行
val+=side#或-=/*=/=。。记住边是一个字符串
input
eval(side1)#或eval(side2)
。除了使用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()
- 它假定不删除运算符
- 删除了每个循环中的
块,只需在计算每边后使用它即可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
核心技巧:
- 用于评估。如果您将此用于任何用途,请注意此技巧的安全含义
- 用于创建要删除的所有可能的字符对
- 不要试图过于特别地处理
,只需在=
check()中捕捉它即可
val=int(side[0])
,这将确保val
的初始值是int
@Cos您打算从用户输入中删除2个字符还是仅从side1中删除?我会根据你的答案,用我到目前为止的想法更新主答案。2个字符可以从我从未使用intertools的任何地方删除,并且我想隐式地这样做。我认为应该允许删除运算符,除了等号。有什么想法吗?•你应该使用itertools——这就是你在Python中的做法。您可以查看user54273的答案,了解如何手动执行。但请记住:这不是蟒蛇式的方法我的代码已经删除了运算符。