I have the following list:
['a', 'b', 'c']
I'm looking into a way to generate all possible strings that contain these characters with the following restrictions:
- a character may not occur multiple times (
aab
,aba
,abca
etc. is invalid) - a character may be excluded (
ab
is valid even ifc
is not present;a
is also valid even ifb
andc
are not present)
I can use
[''.join(p) for p in permutations('abc')]
to generate all strings that contain a
, b
and c
. However I have to also do
[''.join(p) for p in permutations('ab')]
[''.join(p) for p in permutations('ac')]
[''.join(p) for p in permutations('bc')]
As you can probably tell if the initial list of available characters is long I need to do a lot of work. So I'm looking for an elegant way in Python to generate all of the above with just the list of allowed characters as input:
def generate(vals=['a', 'b', 'c']):
# The initial list of allowed characters also has to be part of the
# final list since these also represent valid values
res = vals
# Generate all possible strings and store in res
return res
I need this since I want to provide a parameter for a POST request for my web server, where a parameter (let's call it val
) can take different unique values (either single characters or a combination of those) in order to trigger some data generation. The list of available values will grow over time so I'd like to make it easier to process the request by automating the check if the given values for val
is a valid one.
I've been also thinking of iterating through each element of the list of allowed characters and concatenating it the rest ('a', 'ab', 'ac', 'abc', 'b', 'ba', 'bc' etc.) but I have no idea how to do that.