Search code examples
pythoncpu-wordletter

All possible words from letters in Python


In my program, the user will enter the letters(max is 5), and program will generate all possible words from those letters. For example the user will enter "a b c". Words will be "abc", "acb" , "bac", "bca", "cab" and "cba".

How can i do it? I cannot find an algorithm. Thanks for your help.

Thanks for everyone for helps. I am beginner. I've learned permutation function new :)


Solution

  • import itertools
    
    In [146]: list(itertools.permutations('abc'))
    Out[146]: 
    [('a', 'b', 'c'),
     ('a', 'c', 'b'),
     ('b', 'a', 'c'),
     ('b', 'c', 'a'),
     ('c', 'a', 'b'),
     ('c', 'b', 'a')]
    
    In [147]: [''.join(p) for p in itertools.permutations('abc')]
    Out[147]: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']