word = "word"
# Splitting word into its characters
newword = []
for char in word:
newword.append(char)
print newword
#getting all permutations
test= []
for i in newword:
for j in newword:
if i != j:
for k in newword:
if j != k and i!= k:
for l in newword:
if i != l and j != l and k != l:
test.append(i+j+k+l)
print test
print type(test)
print len(test)
These 4 nested loops work nicely for 'word' because it has exactly 4 letters in it. If I wanted as many 'for' loops as there are letters in any given word, how can I do this? Any nice tricks?
In [10]: import itertools
In [11]: word = "word"
In [12]: test = [''.join(perm) for perm in itertools.permutations(word)]
In [13]: test
Out[13]:
['word',
'wodr',
'wrod',
'wrdo',
'wdor',
'wdro',
'owrd',
'owdr',
'orwd',
'ordw',
'odwr',
'odrw',
'rwod',
'rwdo',
'rowd',
'rodw',
'rdwo',
'rdow',
'dwor',
'dwro',
'dowr',
'dorw',
'drwo',
'drow']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With