The Concept Behind itertools's product Function

不想你离开。 提交于 2019-12-14 03:33:07

问题


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 ()
            return
        if any(len(pool) == 0 for pool in pools):
            return
        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:
                    continue
                indices[i] += 1
                for j in range(i+1, n):
                    indices[j] = 0
                yield tuple(pool[i] for pool, i in zip(pools, indices))
                break
            else:
                return

回答1:


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
    AB.append(t.replace('0','A').replace('1','B'))

n being the string size wanted




回答2:


I would highly recommend using the well established and tested itertools standard 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 = []
def permutations(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:

for i in alphabet:
    for j in alphabet:
        for k in alphabet:
            for l in alphabet:
                result.append(i + j + k + l)



回答3:


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

def generate_arrangements(n):
    return [bin(i)[2:].zfill(n) for i in range(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]


来源:https://stackoverflow.com/questions/38571501/the-concept-behind-itertoolss-product-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!