Zoom
Zoom

Reputation: 21

How can I write a recursion for this function?

How can I write a recursion for this function?

def randomWord(args):
    yield random.choice(args)

list = ['book', 'apple', 'word']
books = randomWord(list)
print(next(books))
print(next(books))
print(next(books))
print(next(books))
print(next(books))

After each print(next(books)) I need to get a random word from list

Upvotes: 0

Views: 57

Answers (2)

Daniel
Daniel

Reputation: 131

Since Python 3.3 you can just use the yield from keyword.

def randomWord(args):
    yield random.choice(args)
    yield from randomWord(args)

list = ['book', 'apple', 'word']
books = randomWord(list)
print(next(books))
print(next(books))
print(next(books))
print(next(books))
print(next(books))

Upvotes: 1

zr0gravity7
zr0gravity7

Reputation: 3194

def randomWord(args):
    yield random.choice(args)

list = ['book', 'apple', 'word']
books = randomWord(list)

def recurse(n):
    if n == 0: return # base case

    print(next(books))
    recurse(n-1)

recurse(99) # the recurse function will call itself 99 times (for a total of 100 calls)

Not sure why you would want this as opposed to a loop...

Upvotes: 0

Related Questions