A small but efficient recursive function for printing the permutation of characters in a given string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#!/usr/bin/env python __version__ = "1.1" """permute.py-- A small but efficient recursive function for printing the permutation of the characters of the specified string. """ import sys def printList(alist, blist=): if not len(alist): print ''.join(blist) for i in range(len(alist)): blist.append(alist.pop(i)) printList(alist, blist) alist.insert(i, blist.pop()) if __name__ == '__main__': k='love' if len(sys.argv)>1: k = sys.argv printList(list(k))
Done initially as a programming excercise this script uses stacks to build the permutations of the characters in the specified string. This does not check for duplicate characters in the specified string but could be modified easily to do so too. Even though the algorithm above uses text/strings as an example, this can easily be used to work with lists of any sort.
I also plan to submit one that does combinations.