-1
\$\begingroup\$

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
\$\endgroup\$
  • \$\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
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\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
1
\$\begingroup\$

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]
\$\endgroup\$

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