Last active
November 18, 2016 14:26
-
-
Save lotka/04c728c7128d9339966d44c9ecb903b1 to your computer and use it in GitHub Desktop.
Two functions for collapsing links which are defined as python lists
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
from copy import copy | |
def collapse_links(links): | |
""" | |
Example: | |
>>> collapse_links([[0],[1,2],[2,3],[3,4],[4,5],[5]]) | |
[[0], [1, 2, 3, 4, 5]] | |
""" | |
# Pointers | |
left = 0 | |
right = 1 | |
links = copy(links) | |
for i in xrange(1,len(links)): | |
if links[left][-1] == links[right][0]: | |
if len(links[right]) > 1: | |
# Add link | |
links[left] += [links[right][-1]] | |
# Mark for removal | |
links[right] = None | |
else: | |
left = right | |
right += 1 | |
return filter(None,links) | |
def collapse_links_with_mask(links,mask): | |
""" | |
Example: | |
>>> collapse_links_with_mask([[0],[1,2],[2,3],[3,4],[4,5],[5],[6],[7],[8]],[0,1,1,2,3,4,5,6,6]) | |
[[0], [1, 2, 3, 4, 5], [6], [7]] | |
""" | |
# Pointers | |
left = 0 | |
right = 1 | |
links = copy(links) | |
for i in xrange(1,len(links)): | |
if mask[links[left][-1]] == mask[links[right][0]]: | |
if len(links[right]) > 1: | |
# Add link | |
links[left] += [links[right][-1]] | |
# Mark for removal | |
links[right] = None | |
else: | |
left = right | |
right += 1 | |
return filter(None,links) | |
collapse_links([[0],[1,2],[2,3],[3,4],[4,5],[5],[6],[7],[8]]) | |
collapse_links_with_mask([[0],[1,2],[2,3],[3,4],[4,5],[5],[6],[7],[8]],[0,1,1,2,3,4,5,6,6]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment