Atichard Chintakanond Atichard Chintakanond - 1 year ago 65
Python Question

The Concept Behind itertools's product Function

so basically i want to understand the concept of product() function in itertools. i mean what is the different between yield and return. And can this code be shorten down anyway.

def product1(*args, **kwds):
pools = map(tuple, args) * kwds.get('repeat', 1)
n = len(pools)
if n == 0:
yield ()
if any(len(pool) == 0 for pool in pools):
indices = [0] * n
yield tuple(pool[i] for pool, i in zip(pools, indices))
while 1:
for i in reversed(range(n)): # right to left
if indices[i] == len(pools[i]) - 1:
indices[i] += 1
for j in range(i+1, n):
indices[j] = 0
yield tuple(pool[i] for pool, i in zip(pools, indices))

Answer Source

This code should do the work:

bytes = [i for i in range(2**(n))]
AB= []
for obj in bytes:
    t = str(bin(obj))[2:]
    t= '0'*(n-len(t)) + t

n being the string size wanted

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download