user1641774
user1641774

Reputation:

Generators in python not working as expected

I have the following code which is not working for me:

def bitmask_generator(n):
    if n > 0:
        for x in bitmask_generator(n-1):
            yield 1 + (x << 1)
        for x in bitmask_generator(n-1):
            yield x << 1

...

for x in bitmask_generator(5):
    print x

The code is supposed to generate all possible bitmasks with length n. However, it prints nothing. What am I doing wrong here?

Update: adding a print(n) on the first line of bitmask_generator does actually print a bunch of n values.

Upvotes: 0

Views: 82

Answers (2)

dwalsh84
dwalsh84

Reputation: 61

You need to add a yield statement before the first for statement. It is a requirement of recursive generators.

def exampleGen(item):
    yield item

    for x in exampleGen(getNextValueFuntion(x)):
        yield x

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124748

Your innermost generator will not generate anything; when n > 0 is false, the function just returns. As such, your outer generator functions have nothing to loop over.

Say you called bitmask_generator(1); it would call bitmask_generator(0) twice. Each such generator would produce an empty sequence, so both for loops in the bitmask_generator(1) stack frame have nothing to loop over, so no yield is ever reached.

Upvotes: 1

Related Questions