Skip to content

Instantly share code, notes, and snippets.

@BennettRand
Last active May 12, 2017 19:15
Show Gist options
  • Save BennettRand/4f64acff4c9710ddeb9eb2c04eed9f3c to your computer and use it in GitHub Desktop.
Save BennettRand/4f64acff4c9710ddeb9eb2c04eed9f3c to your computer and use it in GitHub Desktop.
My answer to my interview question. Create an object to store IP ranges as a blacklist and return if an IP is in the blacklist. Assume no range overlap.
def ip2int(ip):
o = map(int, ip.split('.'))
res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
return "{:0>32b}".format(res)
class BlacklistNode(object):
def __init__(self, parent=None):
self.parent = parent
self.branches = {}
self.blocked = False
class IPBlacklist(object):
def __init__(self):
self.root = BlacklistNode()
def get_last(self, ip_str, create=False):
curr = self.root
for b in ip_str:
if b not in curr.branches:
if create:
curr.branches[b] = BlacklistNode(parent=curr)
else:
return curr
curr = curr.branches[b]
return curr
def put(self, ip, subnet=32):
bin_ip = ip2int(ip)[:subnet]
last = self.get_last(bin_ip, True)
last.blocked = True
return last
def get(self, ip):
bin_ip = ip2int(ip)
last = self.get_last(bin_ip)
return last.blocked
bl = IPBlacklist()
bl.put('10.11.2.0', 24)
bl.put('10.11.3.0', 24)
print bl.get('10.11.2.5') #T
print bl.get('10.11.4.5') #F
print bl.get('10.11.3.5') #T
print bl.get('10.11.3.10') #T
print bl.get('10.12.2.5') #F
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment