0

I'm reading this book on decision trees and in one section the author gave us an example of code for generating a power set. The explanation is god-awful and while i understand the syntax and meanings of all the operations. I'm not getting the reasoning behind this algorithm

# generate all combinations of N items
def powerSet(items):
    N = len(items)
    # enumerate the 2**N possible combinations
    for i in range(2**N):
        combo = []
        for j in range(N):
            # test bit jth of integer i
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        yield combo
ChrisIkeokwu
  • 121
  • 1
  • 1
  • 9

1 Answers1

0

Generators are very efficient method to iterate over big iterators.

It can be called once ! It can make the code return many values by 'yield' instead of return in functions, which return a whole array, a generator yields one value at a time. This requires less memory.

yield combo ill generate combo

(2**N) times after

anati
  • 264
  • 2
  • 13