This question already has an answer here:

Given a string of English alphabet characters, write the shortest code to print all possible permuations in lexicographical order without using any language based library.

def function('bca'):
    return all_permutation.

This should return :


marked as duplicate by Peter Taylor, plannapus, ProgramFOX, Doorknob, John Dvorak Apr 9 '14 at 12:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • \$\begingroup\$ The code-golf and fastest-code tags are very often not compatible... \$\endgroup\$ – Mathieu Rodic Apr 9 '14 at 10:52
  • \$\begingroup\$ The previous question Code-Golf: Permutations didn't impose the lexicographic order, but I think most answers provide it anyway and for those that don't it's a trivial change to call sort. \$\endgroup\$ – Peter Taylor Apr 9 '14 at 11:14
  • \$\begingroup\$ Its about lexicographical order \$\endgroup\$ – Arya Apr 9 '14 at 11:16

Python - 131 129 chars

def g(a,z):
 if len(a)<1:print(z)
  for i in range(len(a)):g(a[:i]+a[i+1:],z+a[i])
def f(s):

Only after coding it I noticed that you wrote both "print" and "return" in the question... my solution prints the permutations, I hope that's alright.

  • \$\begingroup\$ you can combine entire f(s) into g(list(s).sort(),'') \$\endgroup\$ – user80551 Apr 9 '14 at 11:55
  • \$\begingroup\$ The sort function doesn't return the sorted list... but apparently there's a sorted function that does that, which is great to know. \$\endgroup\$ – Tal Apr 9 '14 at 12:37

Python - 83 bytes

p=lambda a,*s:sorted(sum([p(a[:i]+a[i+1:],a[i],*s)for i in range(len(a))],[]))or[s]

Sample usage:

>>> p=lambda a,*s:sorted(sum([p(a[:i]+a[i+1:],a[i],*s)for i in range(len(a))],[]))or[s]
>>> p('abc')
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

Without the sorted call, this narrowly beats out ugoren's answer to the linked question at 75:

p=lambda a,*s:sum([p(a[:i]+a[i+1:],a[i],*s)for i in range(len(a))],[])or[s]

Not the answer you're looking for? Browse other questions tagged or ask your own question.