-2

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 :)

Uğur
  • 47
  • 1
  • 7

2 Answers2

9
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']
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
3
>>> import itertools
>>> for word in itertools.permutations("abc"):
...   print word, ''.join(word)
...
('a', 'b', 'c') abc
('a', 'c', 'b') acb
('b', 'a', 'c') bac
('b', 'c', 'a') bca
('c', 'a', 'b') cab
('c', 'b', 'a') cba
Claudiu
  • 224,032
  • 165
  • 485
  • 680