Skip to content

Instantly share code, notes, and snippets.

@deliro
Created July 6, 2018 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deliro/4058f2566b354d4f87e25cbc4ee89027 to your computer and use it in GitHub Desktop.
Save deliro/4058f2566b354d4f87e25cbc4ee89027 to your computer and use it in GitHub Desktop.
Find a subnet that contains ip
from heapq import heappush
from functools import total_ordering, reduce
def ip(s):
return reduce(lambda r, c: c + (r << 8), map(int, s.split(".")), 0)
@total_ordering
class Subnet:
def __init__(self, start, end):
self.start = start
self.end = end
def __str__(self):
return f"{self.start}-{self.end}"
def __repr__(self):
return f"Subnet({self.start}, {self.end})"
def __eq__(self, other):
return self.start == other.start and self.end == other.end
def __lt__(self, other):
return self.start < other.start
def __getitem__(self, i):
if i == 0:
return self.start
return self.end
class SubnetStorage:
def __init__(self):
self.heap = []
def insert(self, subnet):
heappush(self.heap, subnet)
def find(self, ip):
first = 0
last = len(self.heap) - 1
while first <= last:
i = (first + last) // 2
if self.heap[i][1] >= ip >= self.heap[i][0]:
return self.heap[i]
elif self.heap[i][0] > ip or self.heap[i][1] > ip:
last = i - 1
elif self.heap[i][0] < ip or self.heap[i][1] < ip:
first = i + 1
else:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment