-1

How do I take, for example, this tuple ("A", "E", "L") and generate all possible words without repeating the letters? The result would be 3 words with only one letter, 6 words with two letters and 6 words with 3 letters.

I tried this:

def gererate(tuplo_letras):
    return [i for i in itertools.permutations(tuplo_letras)]

def final(arg):
    return generate(list(map(''.join, itertools.permutations(arg))))
user2390182
  • 72,016
  • 6
  • 67
  • 89
Pereira
  • 13
  • 2

1 Answers1

1

You can use itertools.permutations and iterate over all the lengthes of the permutations you want to cover. Note that permutations takes two arguments, the iterable and the desired length of the permutations you want:

from itertools import permutations, chain

tpl = ("A", "E", "L")
[''.join(p) for p in chain(*(permutations(tpl, l+1) for l in range(len(tpl))))]
# ['A', 'E', 'L', 'AE', 'AL', 'EA', 'EL', 'LA', 'LE', 'AEL', 'ALE', 'EAL', 'ELA', 'LAE', 'LEA']

If you need them grouped you can nest the comprehensions accordingly:

[[''.join(p) for p in (permutations(tpl, l+1))] for l in range(len(tpl))]
# [['A', 'E', 'L'], ['AE', 'AL', 'EA', 'EL', 'LA', 'LE'], ['AEL', 'ALE', 'EAL', 'ELA', 'LAE', 'LEA']]
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • And how do I create new lists based on the length of the words? I mean, put in one lists all the words with one letter, in another list the words with two words and so on? – Pereira Dec 03 '17 at 12:17
  • Updated it with a nested list grouped by length variant. – user2390182 Dec 03 '17 at 12:20
  • And if I had to select words based on another condition how would I do that? – Pereira Dec 03 '17 at 12:23
  • One question at a time ... but you can add an if clause to the comprehensions: `[x for y in lst if condition(x)]` – user2390182 Dec 03 '17 at 12:33
  • Because I have another function that decides if the words are valid or not and I want to choose from the list above the the which are valid. – Pereira Dec 03 '17 at 12:36