Search code examples
pythonpermutationpython-itertools

Python itertools permutations how to include repeating characters


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?


Solution

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