Skip to content
Advertisement

Generating all possibilities of a string given a list of chars but want only the strings up to n length

I have written the below code to recursively generate all of the possible combinations of a string.

JavaScript

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

However ideal output when n = 2 would appear as.

JavaScript

When I change length to 2 then the output is:

JavaScript

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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement