-2

I'm pretty new to python and I need to create a list of strings from all possible permutations of the letters in the list (letters_guessed). but the problem is I get a list that looks like this:

[('a', 'b', 'c', 'd'), ('a', 'b', 'd', 'c'), ('a', 'c', 'b', 'd'), ('a', 'c', 'd', 'b'), ('a', 'd', 'b', 'c'), ('a', 'd', 'c', 'b'), ('b', 'a', 'c', 'd'), ('b', 'a', 'd', 'c'), ('b', 'c', 'a', 'd'), ('b', 'c', 'd', 'a'), ('b', 'd', 'a', 'c'), ('b', 'd', 'c', 'a'), ('c', 'a', 'b', 'd'), ('c', 'a', 'd', 'b'), ('c', 'b', 'a', 'd'), ('c', 'b', 'd', 'a'), ('c', 'd', 'a', 'b'), ('c', 'd', 'b', 'a'), ('d', 'a', 'b', 'c'), ('d', 'a', 'c', 'b'), ('d', 'b', 'a', 'c'), ('d', 'b', 'c', 'a'), ('d', 'c', 'a', 'b'), ('d', 'c', 'b', 'a')]

Is there a way I can bind the characters into strings? I tried using this:

for i in range(0, len(t)):
    words_guessed = (''.join(t[i]))

but that creates a list of lines which I then can't convert into a list of strings

code:

import itertools
letters_guessed = ['a', 'b', 'c', 'd']
t = list(itertools.permutations(letters_guessed, 4))
for i in range(0, len(t)):
    words_guessed = (''.join(t[i]))
print(t)
Yashik
  • 391
  • 5
  • 17
  • 1
    your `''.join` should work... you just don't use the result anywhere (try printing `word_guessed`) – Adam.Er8 Jun 26 '19 at 09:34

1 Answers1

2

The simplest way to do this would be using map to join the resulting tuples into strings:

list(map(''.join, t))
# ['abcd', 'abdc', 'acbd', 'acdb', 'adbc'...

Note that with the following:

for i in range(0, len(t)):
    words_guessed = (''.join(t[i]))

You're not doing anything with the result of joining a given tuple. You're just overwritting words_guessed at each iteration. You could iterate over the generated permutations and append them to words_guessed being a list:

words_guessed = []
for i in permutations(letters_guessed, 4):
    words_guessed.append(''.join(i))
yatu
  • 86,083
  • 12
  • 84
  • 139