Skip to content

Instantly share code, notes, and snippets.

@bdw
Created March 21, 2014 23:02
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 bdw/9698303 to your computer and use it in GitHub Desktop.
Save bdw/9698303 to your computer and use it in GitHub Desktop.
An algorithm to compact arrays (python). I figured it out but I can't explain why it works.
def compact(a_list):
# strategy - find the first empty and nonempty items
empty, nonempty = 0, 0
while empty < len(a_list) and nonempty < len(a_list):
# ok, so in principle this works really well... why?
# what happens is that nonempty looks for the earliest nonempty
# element and empty looks for the earliest empty element
if a_list[nonempty] is None:
nonempty += 1
elif not a_list[empty] is None:
empty += 1
# if both a nonempty and an empty element are found, switch them
# but only if the empty was found 'earlier' than the nonempty position
elif empty < nonempty:
a_list[empty] = a_list[nonempty]
a_list[nonempty] = None
empty += 1
else:
nonempty += 1
return a_list[:empty]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment