I am trying to use itertools.combinations to return all the combinations of letters in alphabet with length at most n.
def string_combinations(alphabet, n):
'''
Parameters
----------
alphabet : {str}
n : {int}
Returns
-------
list : {list} of {str}
Example
-------
>>> string_combinations('abc', 2)
['a', 'b', 'c', 'ab', 'ac', 'bc']
'''
So far I have
return [str(x) for i in range(1,n+1) for x in itertools.combinations(alphabet,i)]
but itertools.combinations
returns tuples in a list [('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c')]
How should I achieve my desired solution?
You can concatenate all the strings returned by itertools
:
result = map("".join, (comb for i in range(1, n+1) for comb in itertools.combinations(alphabet, i)))
This is equivalent to putting a call to "".join
inside a list comprehension:
result = ["".join(comb) for ...]
"".join(iterable)
concatenates all the string that are retrieved from an iterable:
"".join(('a', 'b', 'c')) == "abc"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.