18

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?

Community
  • 1
  • 1
jkdba
  • 2,093
  • 3
  • 19
  • 31

2 Answers2

43

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
  • 345,440
  • 70
  • 544
  • 649
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
  • 31,546
  • 5
  • 54
  • 98
  • 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