computing the occurences of a number in a list with recursion
python, recursion
Solution
You normally return the total count:
def array11(arr, index):
if index == len(arr):
return 0
return (arr[index] == 11) + array11(arr, index + 1)
I am using a little Python trick here where `bool` is a subclass of `int` and `True` is equal to 1. As such, adding up booleans (or booleans and integers) results in the boolean values to be interpreted as integer numbers instead.
You'd use `print` then on whatever the outermost call to `array11()` returned.
Problem
the task I am doing is: Given an array of ints, compute recursively the number of times that the value 11 appears in the array. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. I need to do this recursively. I'm rather new at this, but I technically made it work. I have the following: ``` def array11(arr, index, cnt=0, num=0): if(cnt==len(arr)-index): print("yay!!! number 11 appears %d times"%num) return elif(arr[index:][cnt]==11): num+=1 cnt+=1 array11(arr,index,cnt,num) else: cnt+=1 array11(arr,index,cnt,num) ``` but I feel I did it a cheap way for some reason by adding the "cnt" and "num" parameters with default values. I just didn't know how to go through the "arr" array without a counter!! So this this something acceptable? Would you have done it the same way? thanks in advance