简体   繁体   English

并非所有排列都包括 [itertools, permutations]

[英]Not all permutations included [itertools, permutations]

In my code below a list (coins) is given and from that list, it prints all the permutations of the sum of 3 numbers in coins that add up to 65.在我下面的代码中,给出了一个列表(硬币),并且从该列表中,它打印出硬币中 3 个数字总和的所有排列,这些数字总和为 65。

However, in my opinion, it should also print the permutations of the numbers 30, 30, and 5:但是,在我看来,它还应该打印数字 30、30 和 5 的排列:

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

Now it will only print:现在它只会打印:

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

My code:我的代码:

coins = [50, 30, 10, 5]

from itertools import permutations

perm = permutations(coins, 3)


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

How can these permutations be included without just adding them to the code?如何在不将它们添加到代码中的情况下包含这些排列?

You need product instead of permutations您需要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)

There is only one 30 in your list;您的列表中只有一个30 permutation will only permute the existing elements of your list. permutation只会排列列表中的现有元素。

You can multiply your list with the length you choose each permutation to be, and add a set() wrapper to remove the duplicates:您可以将列表与您选择的每个排列的长度相乘,并添加一个set()包装器以删除重复项:

from itertools import permutations

coins = [50, 30, 10, 5]

for i in set(permutations(coins * 3, 3)):
    if sum(i) == 65:
        print(i)

Output:输出:

(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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM