# All possible permuations in lexicographical order [duplicate]

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 :

abc,
acb,
bac,
bca,
cab,
cba

• The code-golf and fastest-code tags are very often not compatible... – Mathieu Rodic Apr 9 '14 at 10:52
• 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. – Peter Taylor Apr 9 '14 at 11:14
• Its about lexicographical order – Arya Apr 9 '14 at 11:16

# Python - 131 129 chars

def g(a,z):
if len(a)<1:print(z)
else:
for i in range(len(a)):g(a[:i]+a[i+1:],z+a[i])
def f(s):
a=list(s)
a.sort()
g(a,'')


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.

• you can combine entire f(s) into g(list(s).sort(),'') – user80551 Apr 9 '14 at 11:55
• The sort function doesn't return the sorted list... but apparently there's a sorted function that does that, which is great to know. – 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]