For educational purposes of understanding recursion I would like to solve the following problem: given a list of integers foo
in which 0
is guaranteed, I would like to choose a number from that list randomly until either the random generator chooses 0
or until it works 100
times.
Iteratively speaking, my solution looks like this:
def num_random(foo):
nums = 0
x = math.inf
while nums < 100 and x != 0:
x = random.choice(foo)
nums += 1
return nums
My recursive version of the same function is this:
def count_random(foo, number):
x = random.choice(foo)
print("x = {0}".format(x)) # debug purposes
if x != 0 and number < 100:
count_random(foo, number + 1)
else:
return number
Initial call:
print(count_random([0, 1, 2, 3, 4, 5], 0))
The problem with the recursive solution is that it always returns None
and I don't understand why. My reasoning: if the chosen number is not 0
, we know that the number of integers in the next call will be the number of integers in the current call plus 1. If the randomly chosen integer is 0
, we need to return the number of integers in the outer scope. However, my function always returns None
.
Why does my function always return None
and how do I fix it?