1

I have a generator function that yields the power set of a list. I put some print statements in it, but when I run the project none of them print anything. If I write a function that just prints 'test' it works however. Could someone please help?

def powerSet(items):
    print 'test'
    N = len(items)
    print N
    for i in range(2**N):
        combo = []
        for j in range(N):
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        print combo
        yield combo

list = ['a', 'b', 'c']
powerSet(list)
Big_Mac
  • 2,634
  • 3
  • 17
  • 32
  • iterate powerSet(list) – Haifeng Zhang Jun 20 '17 at 22:08
  • 4
    Its a very bad idea to use the name of a builtin like `list` as a variable in your own code. The natural way to consume a generator like this would be `list(generator(whatever))`, but since you've rebound the name `list`, that won't actually work correctly. – Blckknght Jun 20 '17 at 22:16

3 Answers3

2

Generators require iteration so their values would be generated:

def powerSet(items):
    N = len(items)
    for i in range(2**N):
        combo = []
        for j in range(N):
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        yield combo

list = ['a', 'b', 'c']
for x in powerSet(list):
    print(x)
Uriel
  • 13,905
  • 4
  • 21
  • 43
1
powerSet(list)

This returns the generator, not the series of values. To get the values, I think you want something like the comprehension below:

>>> powerSet(list)
<generator object powerSet at 0x7f486b44ab90>
>>> [p for p in powerSet(list)]
test
3
[]
['a']
['b']
['a', 'b']
['c']
['a', 'c']
['b', 'c']
['a', 'b', 'c']
[[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
Prune
  • 72,213
  • 14
  • 48
  • 72
1

Do something like this:

def powerSet(items):
    N = len(items)
    for i in range(2**N):
        for j in range(N):
            if (i >> j) % 2 == 1
                yield items[j]

>>> list(powerSet(['a', 'b', 'c']))
['a', 'b', 'a', 'b', 'c', 'a', 'c', 'b', 'c', 'a', 'b', 'c']

Or, if you need a groupped elements:

def powerSet(items):
    N = len(items)
    for i in range(2**N):
        combo = []
        for j in range(N):
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        yield combo

>>> list(powerSet(['a', 'b', 'c']))
 [[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
Chiheb Nexus
  • 7,803
  • 4
  • 25
  • 38