簡體   English   中英

你如何使用字符串來解決使用python的數學方程式?

[英]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

編輯:

  1. 是的,我仍然堅持使用Python 2.7(如果Python 3使用input
  2. 要求解每一方的價值,你可以簡單地使用eval(side1) # or eval(side2) 可能有使用eval替代方案。 (我自己是新手)。 eval還將負責PEMDAS。
  3. 添加了對side1表達式的編輯。
  4. 更新了目前為止編寫的代碼。

     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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM