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 :)
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.