Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple instances of a generator function [duplicate]

Possible Duplicate:
How to clone a Python generator object?

Suppose I have a generator 'stuff_to_try', I can try them one by one but if I had a method that wanted to go through the generator and that method is recursive, I want to let each recursion get a fresh new generator that starts at the first yield rather than where the last recursion left off.

def solve(something):
    if exit_condition(something):
        return

    next_to_try = stuff_to_try.next()
    while not if_works(next_to_try):
        next_to_try = stuff_to_try.next()
    solve(do_something(something))

Of course I can define stuff_to_try inside the recursive function but is there a better way? Is there an equivalent of stuff_to_try.clone().reset() or something?

like image 597
xster Avatar asked Oct 06 '22 15:10

xster


2 Answers

Define the generator in a function:

def stuff_to_try():
    return (i for i in [stuff, to, try])

Then each time you want a new generator, just call the function.

def solve(something):
    if exit_condition(something):
        return

    for next_to_try in stuff_to_try():
        if_works(next_to_try):
            break
    solve(do_something(something))

If I read your question correctly, what you actually want is this:

def solve(something):
    if exit_condition(something):
        return

    for each in [stuff, to, try]:
        if_works(each):
            break
    solve(do_something(something))
like image 162
Lennart Regebro Avatar answered Oct 10 '22 01:10

Lennart Regebro


The simplest answer is make it a list, then it will have the behaviour you want:

stuff_to_try = [i for i in [stuff, to, try]]

Any efficiency gains from being lazy are likely to be lost by recalculating the values again and again.

like image 38
Gareth Latty Avatar answered Oct 10 '22 01:10

Gareth Latty