Python itertools permutations how to include repeating characters

Question:

I have some code like:

def perm(n,i):
    b = 0
    while b < n:
        n= n -1
        from itertools import permutations as p
        file.write('n'.join([''.join(item) for item in p(i,n)]))
perm(4,'0123')

which produces output like:

012
013
021
023
031
032
102
103
120
123
130
132
201
203
210
213
230
231
301
302
310
312
320
321.....

How can I make it so that the output includes permutations that repeat values, like 112 or 222?

Asked By: jkdba

||

Answers:

What you seem to be looking for is a Cartesian product, not a permutation, which is also provided by itertools.

You might do well to familiarize yourself with the differences between permutation, combination, combination with replacement, and Cartesian product to decide what works best your application, but chances are, you’re looking for another of the options.

Answered By: acjay

You don’t want permutations at all. You want the cartesian product:

import itertools

def perm(n, seq):
    for p in itertools.product(seq, repeat=n):
        file.write("".join(p))
        file.write("n")

perm(4, "0123")
Answered By: Ned Batchelder