Reputation: 3
I have two lists, for example:
digits = ['1', '2', '3', '4']
chars = ['!', '@', '#', '$']
And I need to get all permutations without repetition from these two tables, but on the assumption if I use in a combination first element from "digits" table, I cannot use first one from "chars". Same for second, third etc.
Specific order is not important. But in need to work in other lengths of input list. Max length of input lists is 10 and max length of permutations is 10.
For example, 2 chars length permutations need to look like:
12
13
14
21
23
24
31
32
34
41
42
43
!@
!#
!$
@!
@#
@$
#!
#@
#$
$!
$@
$#
!2
!3
!4
@1
@3
@4
#1
#2
#4
$1
$2
$3
1@
1#
1$
2!
2#
2$
3!
3@
3$
4!
4@
4#
I will be grateful for your help, my mind is blowing from thinking about the solution :)
Upvotes: 0
Views: 919
Reputation: 27588
from itertools import permutations, product
digits = ['1', '2', '3', '4']
chars = ['!', '@', '#', '$']
k = 2
for perm in permutations(zip(digits, chars), k):
for prod in product(*perm):
print(''.join(prod))
That's for permutations of length k
. If you want all lengths, replace the hardcoded k
with for k in range(len(digits) + 1):
.
Zipping the lists gives you option pairs:
('1', '!')
('2', '@')
('3', '#')
('4', '$')
Then permutations
gives you permutations of those option pairs:
(('1', '!'), ('2', '@'))
(('1', '!'), ('3', '#'))
(('1', '!'), ('4', '$'))
(('2', '@'), ('1', '!'))
(('2', '@'), ('3', '#'))
(('2', '@'), ('4', '$'))
(('3', '#'), ('1', '!'))
(('3', '#'), ('2', '@'))
(('3', '#'), ('4', '$'))
(('4', '$'), ('1', '!'))
(('4', '$'), ('2', '@'))
(('4', '$'), ('3', '#'))
And then feeding each such permutation into product
gives you permutations of the strings, for example the product of (('3', '#'), ('1', '!'))
gives these:
('3', '1')
('3', '!')
('#', '1')
('#', '!')
Just need to be join
ed then.
Upvotes: 2
Reputation: 4071
You can do something like this:
def calculate(digits, chars):
from itertools import permutations
indices = list(permutations(range(len(digits)), 2))
a = [digits[i] + digits[j] for i,j in indices]
b = [chars[i] + chars[j] for i,j in indices]
c = [chars[i] + digits[j] for i,j in indices]
d = [digits[i] + chars[j] for i,j in indices]
return a + b + c + d
This just computes the permutation indices required. Your goal is to then just combine the values from the indices in the respective arrays. Here, a, b, c, d
are the 4 combinations required to produce your output. Notice how the digits and chars are combined.
Upvotes: 0