Skip to content

Instantly share code, notes, and snippets.

@llimllib
Created January 27, 2010 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save llimllib/287827 to your computer and use it in GitHub Desktop.
Save llimllib/287827 to your computer and use it in GitHub Desktop.
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