我想製作一個採用用戶等式的python程序,例如:「168/24+8=11*3-16
」,並嘗試通過從用戶輸入中刪除任何2個字符來使等式兩邊相等。這是我到目前爲止:如何使用字符串來解決使用python的數學公式?
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
我該如何去做這件事?我對如何真正處理這個程序感到困惑。
我可以有一些組輸入和預期產出的呢? – 2014-09-27 17:04:27
可以說用戶輸入等式168/24 + 8 = 11 * 3-16程序檢查一邊是否等於另一邊,15 = 17,因爲該程序從用戶輸入中刪除2個字符,所以兩邊都是等於,18/2 + 8 = 11 * 3-16,因爲6和4已經被移除,所以現在的等式等於17 = 17 – Cos 2014-09-27 17:25:34
唷!並不像我想的那麼簡單! – 2014-09-27 17:32:28