sten
sten

Reputation: 7476

Permutations with repetitions?

I can do this with itertools :

list(permutations([1,2,3],2))
: [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

but how do I also generate :

 (1,1),(2,2),(3,3)

of course w/o doing it separately : [(i,i) for i in range(4)]

Upvotes: 1

Views: 130

Answers (3)

pylang
pylang

Reputation: 44485

You are seeking a permutations_with_replacement tool.

That will give n**r results, e.g. 3**2 = 9 total results.

Python does not yet implement this tool; reasons unclear. However, permutations can generally be implemented with a Cartesian product.

Code

Modified from the docs:

def permutations_with_replacement(iter_, r=None):
    """Yield all or some permutations from a replenished pool; from docs."""
    pool = tuple(iter_)
    n = len(pool)
    r = n if r is None else r

    for indices in itertools.product(range(n), repeat=r):
        #if len(set(indices)) == r:
            #print(indices)

        yield tuple(pool[i] for i in indices)

Demo

results = list(permutations_with_replacement([1, 2, 3], r=2))
len(results)
# 9

results
# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

Equivalently reduced to:

list(itertools.product([1, 2, 3], repeat=2))
# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

See also more answers to this question from an earlier post.

Upvotes: 1

sten
sten

Reputation: 7476

Nakor got the right answer :

  product([1,2,3], repeat=2)

I made mistake to try :

 list(product([1,2,3],2))

which errors :

  TypeError: 'int' object is not iterable

Upvotes: 0

JavierCastro
JavierCastro

Reputation: 328

Adding to Nakor's comment, it looks like what you want is the cartesian product. You can get that with list(itertools.product([1,2,3],repeat=2)).

Permutations on the other hand, according to the documentation

The code for permutations() can be also expressed as a subsequence of product(), filtered to exclude entries with repeated elements (those from the same position in the input pool)

so it looks like there is no way to use list(itertools.permutations([1,2,3],2)) and get the output that you want without using additional logic.

Upvotes: 3

Related Questions