# Example of incorrect attempt to write recursive function # that counts the number of 0s in a list # # This demonstrate a common (among new-to-recursion students) but # incorrect approach to writing recursive functions. # Usually, people who write code like this believe that the recursive # calls (marked with ***) will update the value of the total # variable at the calling level. But they DO NOT. Each time # count0s is called, a new set 'total' variable is created and only # that new variable is modified. You can "watch" what happens very clearly # if you run this code in pythontutor.com. # # count0sB and counts0sC demonstrate correct ways to solve this problem. # def count0s (inList): total = 0 if inList != []: if inList[0] == 0: total = total + 1 count0s(inList[1:]) # *** recursive call else: count0s(inList[1:]) # *** recursive call return total def count0sB (inList): total = 0 if inList != []: restTotal = count0sB(inList[1:]) if inList[0] == 0: total = 1 + restTotal else: total = restTotal return total def count0sC (inList): if inList == []: return 0 elif inList[0] == 0: return 1 + count0sC(inList[1:]) else: return count0sC(inList[1:])