Reputation: 39
In python 3, I have a variable length list, where each element of the list is a variable length string. Something like this
['TO', 'G', 'ZDO', 'DEO', 'SGT', 'D', 'Z', 'FT', 'OV']
and I want to iterate over every possible combination of words where the letters that make up the word are from the strings in the list, and the length of the word is the same as the length of the list. So something like this
TGZDSDZFO
TGZDSDZFV
TGZDSDZTO
...
OGOOTDZTO
OGOOTDZTV
I am having trouble coming up with a generic solution for n-sized list.
Upvotes: 1
Views: 459
Reputation: 113905
As others have suggested, itertools
is perhaps the simplest/easiest way to solve this. If you are looking to write your own algorithm however (i.e. reimplement what itertools
does under the hood), then take a look at this:
def allPerms(L, sofar=''):
if not L:
print(sofar)
else:
for char in L[0]:
allPerms(L[1:], sofar+char)
Output:
In [97]: L = ['TO', 'G', 'ZDO', 'DEO', 'SGT', 'D', 'Z', 'FT', 'OV']
In [98]: allPerms(L)
TGZDSDZFO
TGZDSDZFV
TGZDSDZTO
TGZDSDZTV
TGZDGDZFO
TGZDGDZFV
TGZDGDZTO
TGZDGDZTV
TGZDTDZFO
TGZDTDZFV
TGZDTDZTO
TGZDTDZTV
TGZESDZFO
TGZESDZFV
TGZESDZTO
TGZESDZTV
TGZEGDZFO
TGZEGDZFV
TGZEGDZTO
TGZEGDZTV
--- truncated ---
EDIT:
As @njzk2 points out, python3's yield-from does a fantastic job of making the output usable:
def allPerms(L, sofar=''):
if not L: yield sofar
else:
for char in L[0]: yield from allPerms(L[1:], sofar+char)
Output:
In [118]: for i in allPerms(L): print(i)
TGZDSDZFO
TGZDSDZFV
TGZDSDZTO
TGZDSDZTV
TGZDGDZFO
TGZDGDZFV
TGZDGDZTO
TGZDGDZTV
TGZDTDZFO
TGZDTDZFV
TGZDTDZTO
TGZDTDZTV
TGZESDZFO
TGZESDZFV
TGZESDZTO
TGZESDZTV
TGZEGDZFO
TGZEGDZFV
TGZEGDZTO
TGZEGDZTV
TGZETDZFO
TGZETDZFV
TGZETDZTO
--- truncated ---
Upvotes: 2
Reputation: 10111
you could use the itertools
module to create the permutations of your desired length.
combine all the workds to one string and use it in the permutations function
lst = ['TO', 'G', 'ZDO', 'DEO', 'SGT', 'D', 'Z', 'FT', 'OV']
length = len(lst)
combined = ''.join(lst)
all_perms = itertools.permutations(combined, length)
#this will give you something like [('T', 'O', ...), (...),]
print ([''.join(x) for x in all_perms])
Upvotes: -4
Reputation: 798456
>>> (''.join(s) for s in itertools.product(*['TO', 'G', 'ZDO', 'DEO', 'SGT', 'D', 'Z', 'FT', 'OV']))
<generator object <genexpr> at 0x7f2a46468f00>
>>> # to demonstrate:
...
>>> list(itertools.islice((''.join(s) for s in itertools.product(*['TO', 'G', 'ZDO', 'DEO', 'SGT', 'D', 'Z', 'FT', 'OV'])), 3))
['TGZDSDZFO', 'TGZDSDZFV', 'TGZDSDZTO']
Upvotes: 8