Reputation: 11
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
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
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 string
s.
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