2017-01-09 96 views
3

有人可以向我解釋爲什麼這不起作用嗎?Python遞歸錯誤

我想創建一個使用遞歸的更改機器。第一個參數是我們需要返還的變化量,第二個參數是第一個元素代表25美元的賬單數量,第二個參數代表50美元,最後一個 代表100美元。

當我打電話checkchange(125,[0,1,1]),現在不返回「T」或「F」 相反,它只是打印出 lets go Bills: 011 Money: 125 ok the money is greater than 100 lets go Bills: 010 Money: 25 this is the money 25

下面是代碼:

def checkchange(money,bills): 
    tot = bills[0] * 25 + bills[1] * 50 + bills[2] * 100 
    print("lets go")  
    string = "".join(str(e) for e in bills) 
    print("Bills: %s Money %d" % (string,money)) 
    if tot < money: 
     return "F" 



    elif money == 25 and bills[0] == 0: 
     return "F" 


    elif money >= 100 and bills[2] > 0: 
     print("ok the money is greater than 100") 
     money -= 100 
     bills[2] -= 1 
     checkchange(money,bills) 
     print("this is the money %d" % money) 
    elif money >= 50 and bills[1] > 0: 
     print("ok the money is greater than 50") 
     money -= 50 
     bills[1] -= 1 
     checkchange(money,bills) 
    elif money >= 25 and bills[0] > 0: 
     print("money is greater than 25") 
     money -= 25 
     bills[0] -=1 
     checkchange(money,bills) 
    else: 
     return "T" 
+5

使用'和',而不是'&' –

+0

請添加輸入數據和預期結果或提供錯誤消息(如果有)。 – ppasler

+0

@ppasler剛剛添加了預期結果 –

回答

2

我假設的條件是錯誤的tot > money應該是!=

def checkchange(money,bills): 
     tot = bills[0] * 25 + bills[1] * 50 + bills[2] * 100 
     print("lets go")  
     if tot != money: 
      return "F" 

     if money == 25 and bills[0] == 0: 
      return "F" 


     if money >= 100 and bills[2] > 0: 
      print("ok the money is greater than 100") 
      money -= 100 
      bills[2] -= 1 
      checkchange(money,bills) 
      print("this is the money %d" % money) 
     if money >= 50 and bills[1] > 0: 
      print("ok the money is greater than 50") 
      money -= 50 
      bills[1] -= 1 
      checkchange(money,bills) 
     if money >= 25 and bills[0] > 0: 
      print("money is greater than 25") 
      money -= 25 
      bills[0] -=1 
      checkchange(money,bills) 

     return "T" 

print checkchange(125,[1,0,1]) 
print checkchange(125,[0,1,1]) 

結果:

lets go 
ok the money is greater than 100 
lets go 
money is greater than 25 
lets go 
this is the money 25 
T 
lets go 
F 
+0

您能否在底部包含這兩個打印件的輸出? – Tagc

+0

看到編輯的文章 – ppasler

+0

我做了,我給了它一個upvote。 – Tagc

3

Python中的符號&bitwise AND操作。它與布爾運算符and不一樣。當你有一個像

if money == 25 & bills[0] == 0: 

這實際上讀爲money == (25 & bills[0]) == 0聲明,因爲&結合比==更加緊密。 Here's a useful chart關於運算符優先級

+0

好的感謝解釋和運算符優先級的信息,我會看看它是否工作! –