How to print all possible permutations (all possible orderings) of the words in Python

2 Answers

0 votes
from itertools import permutations

words = ["word-1", "word-2", "word-3"]

for p in permutations(words):
    print(" ".join(p))



'''
run:

word-1 word-2 word-3
word-1 word-3 word-2
word-2 word-1 word-3
word-2 word-3 word-1
word-3 word-1 word-2
word-3 word-2 word-1

'''

 



answered Apr 14 by avibootz
0 votes
def print_words_permutations(words, current=[]):
    if not words:
        print(" ".join(current))
        return

    for i in range(len(words)):
        remaining = words[:i] + words[i+1:]
        print_words_permutations(remaining, current + [words[i]]) # Recursive

words = ["word-1", "word-2", "word-3"]

print_words_permutations(words)



'''
run:

word-1 word-2 word-3
word-1 word-3 word-2
word-2 word-1 word-3
word-2 word-3 word-1
word-3 word-1 word-2
word-3 word-2 word-1

'''

 



answered Apr 14 by avibootz

Related questions

...