I have written the below code to recursively generate all of the possible combinations of a string.
JavaScript
x
24
24
1
def gen_recur(chr_lst, length, n , s, ls):
2
3
if (n == 0):
4
ls.append(s)
5
return
6
7
for j in range(0, length):
8
str_app = s + chr_lst[j]
9
gen_recur(chr_lst, length, n-1, str_app, ls)
10
return
11
12
def generate_passwords(chr_str, length, ls):
13
chr_lst = [char for char in chr_str]
14
s = ""
15
for n in range(1, length + 1):
16
gen_recur(chr_lst, length, n, s, ls)
17
18
if __name__ == "__main__":
19
chr_str = 'abc'
20
length = len(chr_str)
21
ls = []
22
generate_passwords(chr_str, length, ls)
23
print(ls)
24
However I want to only produce all the possibilities of the string up to a length of n
.
Say the string is 'abc'
, and n=2
.
Instead of outputting all of the possible strings of 'abc'
I only want to output the possible strings that are <= n
in length.
Current output appears as.
JavaScript
1
2
1
['a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc', 'aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa', 'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']
2
However ideal output when n = 2 would appear as.
JavaScript
1
2
1
['a', 'b', 'c', 'aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
2
When I change length to 2 then the output is:
JavaScript
1
2
1
['a', 'b', 'aa', 'ab', 'ba', 'bb']
2
And when I change the length to 4 I get a list index out of range error as expected due to the way I am indexing the list in the functions.
Advertisement
Answer
You can use itertools.permutations
:
JavaScript
1
8
1
from itertools import permutations
2
3
def generate_passwords(chr_str, length):
4
for i in range(1, length+1):
5
yield from map("".join, permutations(chr_str, i))
6
7
print(list(generate_passwords('abc', 2)))
8