Sunday, March 9, 2014

Recursing upwards.

It was pointed out to me that usually when we do recursive things it heads downwards, until we hit a value of 1 or 0.

So I tried to come up with an example of something that would "recurse upwards" so to speak.

Let's say we want to create a list of lottery numbers, well we could use this kind of upward recursion to populate and return a list of however many numbers we want, like this:

from random import randint

def lottery(start: int=1, end: int=49, amount: int=6, numbers: list=None):
        if not numbers:
                numbers = []
        chosen = False
        while not chosen:
                number = randint(start, end)
                if not number in numbers:
                        chosen = True
                        numbers.append(number)
        if len(numbers) < amount:
                lottery(start=start, end=end, amount=amount, numbers=numbers)
        else:
                numbers.sort()
                return numbers
        return numbers

Of course we could do the same thing without recursion, but it's always interesting to experiment!

No comments:

Post a Comment