Python itertools permutations how to include repeating characters

jkdba picture jkdba · Dec 22, 2012 · Viewed 21.2k times · Source

Possible Duplicate:
Power set and Cartesian Product of a set python

With Python Itertools.permutations() I would like to receive and output of permutations with repeating characters. For an example this my function below and its current output.

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

the output is:

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 would I get an output like 112 or 222?

from what I understand combinations are not order specific where permutations are. what I am looking for is finding all combinations then every permutation for each combination. Is this possible?

Answer

Ned Batchelder picture Ned Batchelder · Dec 22, 2012

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