【问题标题】:The Concept Behind itertools's product Functionitertools 产品功能背后的概念
【发布时间】:2016-11-29 00:24:23
【问题描述】:

所以基本上我想了解 itertools 中 product() 函数的概念。我的意思是收益和回报之间有什么区别。这段代码是否可以缩短。

    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

【问题讨论】:

  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的编码人员编写代码,但他们通常只有在发布者已经尝试自己解决问题时才会提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出和您实际获得的输出(输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask
  • 没有itertools ?然后我猜是循环时间。您是否有理由不使用 itertools ?还是更像是对自己的挑战?
  • 1.使用 itertools 编写代码。 2. 转到 itertools 文档。对于您使用的每个函数,找到“此函数等效于以下代码:”块。 3. 将这些块复制到您的代码中。
  • 如果它总是AB -- 你可以使用bin() 得到0到2**n-1范围内所有数字的二进制扩展,然后替换@ 987654329@ by A1 by B 在结果字符串中。
  • 我强烈推荐使用成熟且经过测试的itertools 标准模块。作为程序员,从不建议重新发明轮子。话虽如此,我们在这里没有尝试任何代码,只是请求答案(听起来有点像家庭作业)。我将首先查看 itertools 中的 product() 函数。

标签: python recursion itertools


【解决方案1】:

我强烈建议使用成熟且经过测试的itertoolsstandard module。作为程序员,从不建议重新发明轮子。也就是说,我先看看 itertools 中的 product() 函数。

至于不使用itertools(),这个问题本质上是一个笛卡尔积问题(允许重复的n-排列)。这就是递归帮助我们的地方!以下一种可能的解决方案:

方法体:

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

当我们用permutations()打电话时

样本输出:

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']

它是如何工作的?

此方法通过以递归方式重复次嵌套for循环来工作。然后我们累积子解决方案的结果,附加到结果列表中。因此,如果我们使用 4 作为重复值,则此问题的扩展迭代轨迹如下所示:

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

【讨论】:

  • 这是评论,不是答案。
  • @JohnColeman 添加了答案!希望你改变主意:D
  • 没问题——尽管您可能刚刚发布了一个新答案。哎呀——我什至会投票赞成。
【解决方案2】:

这段代码应该可以完成工作:

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 是想要的字符串大小

【讨论】:

    【解决方案3】:

    首先创建一个包含所有可能排列的列表,这很容易通过对二进制文件求和来实现:

    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
    

    [2:] 对字符串进行切片并从中删除 '0b',然后 zfill(n) 用 0 补全字符串,直到字符串的长度为 n。

    现在将所有 0,1 分别替换为 A,B:

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

    如果你想把所有东西放在一起,你有:

    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]
    

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 2015-05-23
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      • 2020-12-13
      • 2012-09-25
      • 2012-04-17
      • 2014-05-29
      相关资源
      最近更新 更多