samedi 28 février 2015

Generating all strings of length n from given alphabet. Python

So I am currently trying to define a function that will generate a list of all strings of length n from a given alphabet without using imports. I have stumbled upon this code:



def allstrings(alphabet, length):

c = [[]]
for i in range(length):
c = [[x]+y for x in alphabet for y in c]
return c


But this is returning a list of lists consisting of the strings, eg



all_strings({'a', 'b'}, 2)


returns



[['a', 'a'], ['a', 'b'], ['b', 'a'], ['b', 'b']]


But I require it to return a list of the generated strings, eg



['aa', 'ab', 'ba', 'bb']


I am unsure on how to do this. Any help is appreciated. Cheers


Aucun commentaire:

Enregistrer un commentaire