19

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
jkdba
  • 2,378
  • 3
  • 23
  • 33

2 Answers2

47

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")
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
12

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.

acjay
  • 34,571
  • 6
  • 57
  • 100
  • I thought that for a second too, but the OP seems to want both `012` and `102` -- or at least he didn't comment on it in his list -- in which case he's probably after `itertools.product`. – DSM Dec 22 '12 at 22:04