Last active
August 29, 2015 14:10
-
-
Save lukasz-madon/a8da9a6cc09b56803bf9 to your computer and use it in GitHub Desktop.
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
# given list [2, 3, 5, 78] | |
# return 1, 4, 6-77, 79-99 | |
# the range is always <1, 100) | |
def get_ranges(lst, N=100): | |
s = set(lst) | |
filtered = (i for i in xrange(1, N) if not i in s) | |
output2 = [] | |
prev = None | |
skipping = False | |
for num in filtered: | |
if prev and prev + 1 == num: | |
if not skipping: | |
output2.append('%d-' % prev) | |
skipping = True | |
else: | |
if skipping: | |
output2[-1] += str(prev) | |
skipping = False | |
else: | |
output2.append(str(num)) | |
skipping = False | |
prev = num | |
if skipping: | |
output2[-1] += str(N - 1) | |
return ",".join(output2) | |
print "***get_ranges***" | |
n1 = get_ranges([2, 3, 5, 78, 99]) | |
res1 = "1,4,6-77,79-98" | |
print n1, res1 , res1 == n1 | |
n2 = get_ranges([1, 2, 5, 78]) | |
res2 = "3,6-77,79-99" | |
print n2, res2, res2 == n2 | |
n3 = get_ranges([2, 3, 4, 78, 99]) | |
res3 = "1,5-77,79-98" | |
print n3, res3, res3 == n3 | |
# better if N is big | |
def get_ranges2(lst, N=100): | |
current = 1 | |
output = [] | |
for num in lst: | |
if current == num: | |
pass | |
elif current + 1 == num: | |
output.append(str(current)) | |
else: | |
output.append("%d-%d" % (current, num - 1)) | |
current = num + 1 | |
if current + 1 == N: | |
output.append(current) | |
elif current + 1 < N: | |
output.append("%d-%d" % (current, N - 1)) | |
return ",".join(output) | |
print "***get_ranges2***" | |
n1 = get_ranges2([2, 3, 5, 78, 99]) | |
res1 = "1,4,6-77,79-98" | |
print n1, res1 , res1 == n1 | |
n2 = get_ranges2([1, 2, 5, 78]) | |
res2 = "3-4,6-77,79-99" | |
print n2, res2, res2 == n2 | |
n3 = get_ranges2([2, 3, 4, 78, 99]) | |
res3 = "1,5-77,79-98" | |
print n3, res3, res3 == n3 | |
# python int.py | |
# ***get_ranges*** | |
# 1,4,6,6-77,79-99 1,4,6-77,79-98 False | |
# 3,3-4,6-77,79-99 3,6-77,79-99 False | |
# 1,5,5-77,79-99 1,5-77,79-98 False | |
# ***get_ranges2*** | |
# 1,4,6-77,79-98 1,4,6-77,79-98 True | |
# 3-4,6-77,79-99 3-4,6-77,79-99 True | |
# 1,5-77,79-98 1,5-77,79-98 True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment