0

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?

alekscooper
  • 795
  • 1
  • 7
  • 19
  • 2
    Does this answer your question? [Why does my recursive function return None?](https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none) – python_user Jan 31 '21 at 06:43

1 Answers1

2

You are missing the return statement in your recursive call:

def count_random(foo, number):
    x = random.choice(foo)
    print("x = {0}".format(x)) # debug purposes
    if x != 0 and number < 100:
        return count_random(foo, number + 1)
    else:
        return number
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35