Created
January 27, 2010 13:26
-
-
Save llimllib/287827 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def perm1c(lst): | |
"""A modification of perm1b to return a copied list instead of modified in place""" | |
initial = lst[:] | |
yield lst | |
lst = lst[:] | |
if len(lst) == 1: return | |
n = len(lst) - 1 | |
while 1: | |
j = n - 1 | |
while lst[j] >= lst[j+1]: | |
j -= 1 | |
#because this algorithm iterates in lexicographic order, | |
#we know that lst is reverse sorted right now | |
#if j == -1: return #terminate | |
if j == -1: | |
lst.reverse() | |
if lst == initial: #if lst was sorted to begin with | |
return | |
yield lst | |
lst = lst[:] | |
j = n-1 | |
break | |
l = n | |
while lst[j] >= lst[l]: | |
l -= 1 | |
lst[j], lst[l] = lst[l], lst[j] | |
k = j + 1 | |
l = n | |
while k < l: | |
lst[k], lst[l] = lst[l], lst[k] | |
k += 1 | |
l -= 1 | |
if lst == initial: | |
return | |
yield lst | |
lst = lst[:] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment