Reputation: 574
Given a word, print every possible rearrangement of the letters in the word.
word = input("Write your word:")
My attempt is below:
The factorial of len(word) provides the number of permutations.
count = 1
i = len(word)
while i > 0:
count *= i
i-=1
factorial = count # i!
f_minus = int(count/len(word)) # (i - 1)!
print("There are " + str(count) + " ways to arrange " + str(len(word)) \
+ " letters.")
Create a list to append rearranged words.
inside_list = []
for i in range(len(word)):
inside_list.append('')
Create a List to contain each inside_list.
container_list = []
for i in range(factorial):
container_list.append(inside_list)
The variable f_minus provides details about how many times each letter appears at the start of the word . Sticking with 'farm', f_minus = (4-1)! = 6. This tells us that each letter appears in the first position six times. The following for loop prints 'f' six times, followed by six 'a's and so on.
for index in range(factorial):
print(index + 1, word[index//f_minus])
So the following for loop assigns letters to the first element of each nested list.
for index in range(factorial):
container_list[index][0] = word[index//f_minus]
print(container_list)
How can I save the iterations to the list of lists so that the 'f's, 'a's, 'r's and 'm's go into the first element of the nested lists rather than all 'm's? i.e. the first 6 lists have an 'f' as their first element, the next 6 lists have an 'a' as the first element and so on.
Upvotes: 1
Views: 1861
Reputation: 7735
There is already a function called permutations in itertools library for this purpose. You can use that instead of re-inventing the wheel.
from itertools import permutations
word = input("Write your word:")
print (["".join(wd) for wd in permutations(word, len(word))])
>>> Write your word:asd
>>> ['asd', 'ads', 'sad', 'sda', 'das', 'dsa']
Upvotes: 1