Small function to generate every permutation of a given sequence. Works for lists and strings
Python, 8 lines
1 2 3 4 5 6 7 8
def all_perms(str): if len(str) <=1: yield str else: for perm in all_perms(str[1:]): for i in range(len(perm)+1): #nb str[0:1] works in both string and list contexts yield perm[:i] + str[0:1] + perm[i:]
This approach allows you to examine every permutation of a given sequence without sucking up too much memory.
Slightly different version.
Although it does not work the same way with strings.
If you swap the two for-loops, you get a sorted version that humans probably like better:
For input 'ABCD', this produces:
rather than the more "random" looking: