2014-09-27 360 views
1

我想製作一個採用用戶等式的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 

我該如何去做這件事?我對如何真正處理這個程序感到困惑。

+0

我可以有一些組輸入和預期產出的呢? – 2014-09-27 17:04:27

+0

可以說用戶輸入等式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

+0

唷!並不像我想的那麼簡單! – 2014-09-27 17:32:28

回答

2

讓我們來看看初步問題。

  • 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版(使用input如果Python 3)
  2. 爲了解決每一方的價值,你可以簡單地將你se 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塊在每個循環,而不是僅僅在計算每一邊後使用它
+0

如果操作系統使用python3會怎麼樣? – 2014-09-27 17:28:21

+0

我得到的是我的操作正在做一個字符串,這就是爲什麼我得到一個類型錯誤。我不確定如何解決這個問題。 – Cos 2014-09-27 17:31:20

+0

@PadraicCunningham,耶編輯指出。 @Cos你可以簡單地設置'val = int(side [0])',這將確保'val'的初始值是一個'int'。 – 2014-09-27 17:33:49

1

這裏是代碼,它完全符合你的要求:

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()
+0

我從來沒有使用過intertools,並且希望隱式地做到這一點,我認爲應該允許刪除運算符,除了等號。有任何想法嗎? – Cos 2014-09-27 20:26:00

+0

•你應該使用itertools - 這就是你如何在Python中完成的。您可以查看user54273的答案,瞭解如何手動執行此操作。但請記住:這不是執行它的pythonic方式。 •我的代碼已經刪除了操作員。 – Chronial 2014-09-28 10:47:37