Reputation: 2853
Is there any function in python itertools
where all the permutations of numbers that satisfy certain criteria need to be generated.
(a,b,c,d)
set 1 = {1,2,3}
set 2
, where the number of elements set 2 is 196.So a and b should take only values from set 1 and b and c should take values only from set 2. How can I generate all the permutaitons with the said restrictions
I am aware how to generate permutation using itertools
to generate enetries with permutation. But I am having problem when it comes to taking items from two sets
Upvotes: 0
Views: 766
Reputation: 662
If I interpreted your text correctly, the following code should be what you are looking for:
import itertools
set1 = [1,2,3]
set2 = [4,5]
for i in itertools.permutations(set1, 2):
for j in itertools.permutations(set2, 2):
print("({},{},{},{})".format(i[0], j[0], j[1], i[1]))
Prints
(1,4,5,2)
(1,5,4,2)
(1,4,5,3)
(1,5,4,3)
(2,4,5,1)
(2,5,4,1)
(2,4,5,3)
(2,5,4,3)
(3,4,5,1)
(3,5,4,1)
(3,4,5,2)
(3,5,4,2)
As @spectras suggests, a product is more elegant:
p1 = itertools.permutations(set1, 2)
p2 = itertools.permutations(set2, 2)
for i in itertools.product(p1, p2):
print(i[0][0], i[1][0], i[1][1], i[0][1])
Upvotes: 1