Jordi van Selm
Jordi van Selm

Reputation: 75

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.

However, in my opinion, it should also print the permutations of the numbers 30, 30, and 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?

Upvotes: 2

Views: 228

Answers (2)

Tugay
Tugay

Reputation: 2214

You need product instead of 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)

Upvotes: 3

Red
Red

Reputation: 27557

There is only one 30 in your list; permutation will only permute the existing elements of your list.

You can multiply your list with the length you choose each permutation to be, and add a set() wrapper to remove the duplicates:

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)

Upvotes: 0

Related Questions