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?
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.
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() do ? It returns r length subsequences of elements from the input iterable.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With