Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

I would highly recommend using the well established and tested itertoolsstandard module. Reinventing the wheel is never advisable as a programmer. That said, I would start by taking a look at the product() function in itertools.

As for not using itertools(), this problem is essentially a cartesian product problem (n-permutations with duplicates allowed). This is where recursion helps us! One possible solution below:

Method Body:

result = []
defpermutations(alphabet, repeat, total = ''):
    if repeat >= 1:
        for i in alphabet:
            # Add the subsolutions.     
            permutations(alphabet, repeat - 1, total + i)  

    else:
        result.append(total)
    return result

And when we call with permutations()

Sample Outputs:

permutations('ab', 3) ->
$ ['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']
permutations('ab', 3) ->
$ ['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa',
  'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 
  'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']
permutations('ab', 1) ->
$ ['a', 'b']

How does it work?

This method works by nesting for loops in a recursive manner repeat-times. We then accumulate the result of the sub-solutions, appending to a result list. So if we use 4 as our repeat value, out expanded iterative trace of this problem would look like the following:

foriin alphabet:
    forjin alphabet:
        forkin alphabet:
            forlin alphabet:
                result.append(i + j + k + l)

Solution 2:

This code should do the work:

bytes = [i for i inrange(2**(n))]
AB= []
for obj inbytes:
    t = str(bin(obj))[2:]
    t= '0'*(n-len(t)) + t
    AB.append(t.replace('0','A').replace('1','B'))

n being the string size wanted

Solution 3:

First create a list with all the possible arrangements, that's easily achievable by summing binaries:

defgenerate_arrangements(n):
    return [bin(i)[2:].zfill(n) for i inrange(2**n)]  # 2**n is number of possible options (A,B) n times

The [2:] slices the string and remove '0b' from it and zfill(n) completes the string with 0s until the string has length of n.

Now replace all 0,1 by A,B respectively:

arrangements = [arrangement.replace('0', 'A').replace('1', 'B') for arrangement in generate_arrangements(3)]
print(arrangements)
>> ['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB']

If you want to put all together you have:

def generateAB(n):
    arrangements = [bin(i)[2:].zfill(n) for i in range(2**n)]
    return [arrangement.replace('0', 'A').replace('1', 'B') for arrangement in arrangements]

Post a Comment for "The Concept Behind Itertools's Product Function"