Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python itertools permutations how to include repeating characters [duplicate]

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?

like image 587
jkdba Avatar asked Dec 22 '12 21:12

jkdba


People also ask

How do you implement a combination in Python?

To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.

How do you find the permutation of a list in Python?

The number of permutations on a set of n elements is given by n!. For example, there are 2! = 2*1 = 2 permutations of {1, 2}, namely {1, 2} and {2, 1}, and 3! = 3*2*1 = 6 permutations of {1, 2, 3}, namely {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2} and {3, 2, 1}.

What does Itertools combinations return?

What does itertools. combinations() do ? It returns r length subsequences of elements from the input iterable.


1 Answers

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")
like image 131
Ned Batchelder Avatar answered Sep 22 '22 22:09

Ned Batchelder