【问题标题】:Not all permutations included [itertools, permutations]并非所有排列都包括在内 [itertools, permutations]
【发布时间】:2020-11-22 20:52:37
【问题描述】:

在下面的代码中,给出了一个列表(硬币),并从该列表中打印出硬币中 3 个数字之和的所有排列,加起来为 65。

但是,在我看来,它还应该打印数字 30、30 和 5 的排列:

(30, 30, 5) 
(30, 5, 30)
(5, 30, 30)

现在它只会打印:

(50, 10, 5)
(50, 5, 10)
(10, 50, 5)
(10, 5, 50)
(5, 50, 10)
(5, 10, 50)

我的代码:

coins = [50, 30, 10, 5]

from itertools import permutations

perm = permutations(coins, 3)


for i in list(perm):
    if sum(i)==65:
        print(i)

如何在不将它们添加到代码的情况下包含这些排列?

【问题讨论】:

    标签: python


    【解决方案1】:

    你需要product 而不是permutations

    from itertools import product
    
    coins = [50, 30, 10, 5]
    
    prod = product(coins, repeat = 3)
    
    for i in prod:
        if sum(i) == 65:
            print(i)
    

    【讨论】:

      【解决方案2】:

      您的列表中只有一个30permutation 只会置换列表中的现有元素。

      您可以将列表乘以您选择的每个排列的长度,并添加一个 set() 包装器以删除重复项:

      from itertools import permutations
      
      coins = [50, 30, 10, 5]
      
      for i in set(permutations(coins * 3, 3)):
          if sum(i) == 65:
              print(i)
      

      输出:

      (5, 50, 10)
      (50, 5, 10)
      (30, 5, 30)
      (5, 30, 30)
      (10, 5, 50)
      (30, 30, 5)
      (5, 10, 50)
      (10, 50, 5)
      (50, 10, 5)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-04
        • 1970-01-01
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-22
        相关资源
        最近更新 更多