Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all permutations of string as list of strings (instead of list of tuples)?

The goal was to create a list of all possible combinations of certain letters in a word... Which is fine, except it now ends up as a list of tuples with too many quotes and commas.

import itertools

mainword = input(str("Enter a word: "))
n_word = int((len(mainword)))

outp = (list(itertools.permutations(mainword,n_word)))

What I want:

[yes, yse, eys, esy, sye, sey]

What I'm getting:

[('y', 'e', 's'), ('y', 's', 'e'), ('e', 'y', 's'), ('e', 's', 'y'), ('s', 'y', 'e'), ('s', 'e', 'y')]

Looks to me I just need to remove all the brackets, quotes, and commas.

I've tried:

def remove(old_list, val):
  new_list = []
  for items in old_list:
    if items!=val:
        new_list.append(items)
  return new_list
  print(new_list)

where I just run the function a few times. But it doesn't work.

like image 649
cookie_straws Avatar asked Dec 08 '22 15:12

cookie_straws


1 Answers

You can recombine those tuples with a comprehension like:

Code:

new_list = [''.join(d) for d in old_list]

Test Code:

data = [
    ('y', 'e', 's'), ('y', 's', 'e'), ('e', 'y', 's'),
    ('e', 's', 'y'), ('s', 'y', 'e'), ('s', 'e', 'y')
]

data_new = [''.join(d) for d in data]
print(data_new)

Results:

['yes', 'yse', 'eys', 'esy', 'sye', 'sey']
like image 99
Stephen Rauch Avatar answered Jan 12 '23 21:01

Stephen Rauch