Created
March 18, 2014 03:56
-
-
Save howardhamilton/9613284 to your computer and use it in GitHub Desktop.
Update list of number line intervals with addition of new interval
This file contains 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
#!/usr/bin/python | |
# | |
# run 'python num_line.py -v' to see doctest results. | |
# Howard Hamilton | |
# 17 March 2014 | |
def number_line(L, I): | |
''' | |
Update number line intervals with addition of new interval. | |
If there is an overlap between new and current intervals, | |
create a new interval that covers the overlapped region. | |
:params L: Intervals on number line. | |
:type L: List of (int, int) tuples | |
:params I: Single interval. | |
:type I: Tuple of two ints | |
:returns: Updated intervals on number line. | |
:rtype: List of (int, int) tuples | |
>>> L = [(2,3),(6,7),(8,9),(10,15)] | |
>>> I = (0,1) | |
>>> number_line(L, I) | |
[(0, 1), (2, 3), (6, 7), (8, 9), (10, 15)] | |
>>> I = (4,5) | |
>>> number_line(L, I) | |
[(2, 3), (4, 5), (6, 7), (8, 9), (10, 15)] | |
>>> I = (3,7) | |
>>> number_line(L, I) | |
[(2, 7), (8, 9), (10, 15)] | |
>>> I = (1,2) | |
>>> number_line(L, I) | |
[(1, 3), (6, 7), (8, 9), (10, 15)] | |
>>> I = (16,20) | |
>>> number_line(L, I) | |
[(2, 3), (6, 7), (8, 9), (10, 15), (16, 20)] | |
''' | |
L_prime = [] | |
(a,b) = I | |
for i, (x,y) in enumerate(L): | |
# single interval ahead of interval in line | |
if b < x: | |
# handle edge case at head of list | |
if i == 0 or L[i-1][1] < a: | |
L_prime.extend([(a,b),(x,y)]) | |
else: | |
L_prime.append((x,y)) | |
# single interval behind interval in line | |
elif a > y: | |
# handle edge case at end of list | |
if i == len(L)-1: | |
L_prime.extend([(x,y),(a,b)]) | |
else: | |
L_prime.append((x,y)) | |
# handle overlap cases | |
elif (x <= a and a <= y) or (x <= b and b <= y) or (a < x and b > y): | |
I = (min(a,x),max(b,y)) | |
# This was the step I was missing -- a recursion call | |
# Need to have a break out of loop when done in order | |
# to prevent repeat intervals | |
if i < len(L)-1: | |
L_prime.extend(number_line(L[i+1:],I)) | |
break | |
return L_prime | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment