[英]How do you use a string to solve a math equation using python?
I'm trying to make a python program which takes in a user equation, for example: " 168/24+8=11*3-16
", and tries to make both sides of the equation equal to each other by removing any 2 characters from the user input. 我正在尝试制作一个python程序,它接受一个用户等式,例如:“
168/24+8=11*3-16
”,并试图通过删除任何2来使等式的两边相等用户输入的字符。 This is what I have so far: 这是我到目前为止:
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)
I have edited my compute function. 我编辑了我的计算功能。
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()
For the actual solve
function I want to test all possible pairs for each side of the equation and with every pair removed check if the equation is equal to the other side. 对于实际的
solve
函数,我想测试方程每一侧的所有可能的对,并且每一对都被移除,检查方程是否等于另一侧。 I was thinking of using a for
loop that said: 我在考虑使用
for
循环说:
for i in side1:
j= [:x]+[x+1:y]+[y+1:]
if compute(j)==compute(side2):
val= compute(j)
return val
How should I go about doing this? 我该怎么做呢? I'm getting a little confused on how to really approach this program.
我对如何真正接近这个程序感到有些困惑。
Let's get to the preliminary issues. 让我们来看看初步问题。
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]
. side2 = e[equalsign + 1:] # not e[:equalsign + 1]
。
val = int(side[0]) # not val = side[0] which will make val a string
In the operations part, you are doing val += side # or -= / *= / /= .. remember side is a string
在操作部分,你正在做
val += side # or -= / *= / /= .. remember side is a string
Edits: 编辑:
input
if Python 3) input
) eval(side1) # or eval(side2)
. eval(side1) # or eval(side2)
。 There could be alternatives to using eval
. eval
替代方案。 (I am a novice myself). eval
will also take care of PEMDAS. eval
还将负责PEMDAS。 side1
expression. side1
表达式的编辑。 Updated with code written so far. 更新了目前为止编写的代码。
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()
This is what I have come up with so far (works for your example at least). 这是我到目前为止所提出的(至少适用于你的例子)。
Final edit: Updated code taking into account @Chronical 's suggestions 最终编辑:考虑到@Chronical的建议更新了代码
try-except
block in each loop and instead just use it after calculating each side try-except
块,而不是在计算每一侧后使用它 Here is code that does exactly what you want: 这是完全符合您要求的代码:
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
Core tricks: 核心技巧:
eval()
for evaluation. eval()
进行评估。 If you use this for anything, please be aware of the security implications of this trick. itertools.combinations
to create all possible pairs of characters to remove itertools.combinations
创建要删除的所有可能的字符对 =
too specially – just catch it in check()
=
太特别 - 只需在check()
捕获它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.