john_mon
john_mon

Reputation: 517

Long Permutations from Small Lists

I have a list titled outcomes:

outcomes = ["heads", "tails"]

As you can see, the list has two elements.

If I want to get permutations from the list, I use the itertools python package as follows:

import itertools 

for permutation in itertools.permutations(outcomes, 2):
    print(permutation)

This code produces the following output:

('heads', 'tails')
('tails', 'heads')

The problem comes when I try to create permutations that are longer than my list; i.e. permutations with more than 2 elements. For instance if I try permutations of 3 or more elements, I get no output:

for permutation in itertools.permutations(outcomes, 3):
    print(permutation)

Are there any quick workarounds for this?

Upvotes: 2

Views: 87

Answers (2)

Richard K Yu
Richard K Yu

Reputation: 2202

If you are looking for a (maybe) less efficient (I think product also uses two for-loops) but (definitely) more verbose way to get the same outcome as itertools.product, which BrokenBenchmark has suggested, I have an alternative:

import itertools

outcomes = ["heads", "tails"]

combinations = [] 
for combination in itertools.combinations_with_replacement(outcomes,3):
    combinations.append(combination)

final = []
for combination in combinations:

    final = final + [*itertools.permutations(combination)]


print(list(set(final)))

(I did not know about itertools.product)

Output:

[('heads', 'heads', 'tails'), 
('heads', 'heads', 'heads'), 
('tails', 'tails', 'heads'), 
('tails', 'tails', 'tails'), 
('tails', 'heads', 'heads'), 
('tails', 'heads', 'tails'), 
('heads', 'tails', 'tails'), 
('heads', 'tails', 'heads')]

Upvotes: 3

BrokenBenchmark
BrokenBenchmark

Reputation: 19243

You're looking for itertools.product. A permutation is an ordering of the existing elements. What you're describing is really a Cartesian product.

import itertools 

outcomes = ['heads', 'tails']
for flips in itertools.product(outcomes, repeat=3):
    print(flips)

Upvotes: 4

Related Questions