3.14159
3.14159

Reputation: 11

How do I separate elements from a list of permutations of a string?

I want to create a program that gives all the permutations of a string and then out of list of strings and filter out ones that start with 'o'. I want to find all permutations that start with 'o'.

from itertools import permutations

x = list(permutations('hello'))
y = []

for i in range(0, len(x)):
    if x[i][0] == 'o':
         y.append(x)
         print(y)

I tried it with this code but its giving me a long list.

Upvotes: 1

Views: 94

Answers (2)

fthkrn
fthkrn

Reputation: 11

for i in range(0, len(x)):
    if x[i][0]=='o':
         y.append(x)
         print(y)

In this code, you put all the items in x list which means all permutation, into y list each time. That's why you had a long list.

Try this code.

from itertools import permutations
x=list(permutations('hello'))
y=[]
for i in x:
    if i[0]=='o':
        y.append(i)
print(y)

If you want to get unique list, just change

x=list(permutations('hello')) to x=set(permutations('hello'))

Upvotes: 0

MSeifert
MSeifert

Reputation: 152657

You could filter out the ones that don't start with o (the if ...[0] == 'o' part) before building the complete list:

>>> y = [''.join(perm) for perm in permutations('hello') if perm[0] == 'o']
>>> y
['ohell', 'ohell', 'ohlel', 'ohlle', 'ohlel', 'ohlle', 'oehll', 'oehll', 
 'oelhl', 'oellh', 'oelhl', 'oellh', 'olhel', 'olhle', 'olehl', 'olelh', 
 'ollhe', 'olleh', 'olhel', 'olhle', 'olehl', 'olelh', 'ollhe', 'olleh']

The str.join converts the permutations to whole strings again. Remove it if you want it as tuple of strings.


To improve efficiency you could simply remove the 'o' from 'hello' and prepend it to every permutation of 'hell' to get the same permutations:

>>> ['o{}'.format(''.join(perm)) for perm in permutations('hell')]
['ohell', 'ohell', 'ohlel', 'ohlle', 'ohlel', 'ohlle', 'oehll', 'oehll',
 'oelhl', 'oellh', 'oelhl', 'oellh', 'olhel', 'olhle', 'olehl', 'olelh', 
 'ollhe', 'olleh', 'olhel', 'olhle', 'olehl', 'olelh', 'ollhe', 'olleh']

Upvotes: 3

Related Questions