簡體   English   中英

Python遞歸錯誤

[英]Python Recursion error

有人可以向我解釋為什么這不起作用嗎?

我正在嘗試使用遞歸創建一個更改機器。 第一個參數是我們需要返還的零錢金額,第二個參數是鈔票數量的數組,第一個元素表示 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"

&符號& Python中是bitwise AND運算符。 它與布爾值and運算符不同。 當你有這樣的聲明時

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

這實際上被理解為money == (25 & bills[0]) == 0 ,因為&==綁定得更緊密。 這是有關運算符優先級的有用圖表

我認為條件是錯誤的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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