Created
March 21, 2014 23:02
-
-
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.
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 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