Unify the format of your ips, change the range to a couple of integers.
Now the task is much simpler - to "consolidate" the integer range. I believe that there are many existing efficient algorithms for this, below just my naive attempt:
>>> orig_ranges = [(1,5), (7,12), (2,3), (13,13), (13,17)] # should result in (1,5), (7,12), (13,17) >>> temp_ranges = {} >>> for r in orig_ranges: temp_ranges.setdefault(r[0], []).append('+') temp_ranges.setdefault(r[1], []).append('-') >>> start_count = end_count = 0 >>> start = None >>> for key in temp_ranges: if start is None: start = key start_count += temp_ranges[key].count('+') end_count += temp_ranges[key].count('-') if start_count == end_count: print start, key start = None start_count = end_count = 0 1 5 7 12 13 17
The general idea is as follows: after we put ranges on temp_ranges other (in temp_ranges dict), we can find new compiled ranges simply by counting the initial and final values โโof the original ranges; as soon as we got equality, we found a single range.
Roman bodnarchuk
source share