Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Speedy category for IP Network: Route Summarization by maelnor
from math import floor, log2
from itertools import combinations
def highBit(n):
return floor(log2(n))
def ip2n(ip):
return sum(int(x) << i*8 for i, x in enumerate(reversed(ip.split('.'))))
def n2ip(n):
return '.'.join(str((n >> i*8) % 256) for i in (3, 2, 1, 0))
P32 = 8589934591
def checkio(data):
unprefix = max(map(lambda x: highBit(x[0] ^ x[1]),
combinations(map(lambda x: ip2n(x), data), 2))) + 1
net_addr = ip2n(data[0]) & (P32 << unprefix)
return "%s/%s" % (n2ip(net_addr), 32 - unprefix)
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert (checkio(["172.16.12.0", "172.16.13.0", "172.16.14.0", "172.16.15.0"]) == "172.16.12.0/22"), "First Test"
assert (checkio(["172.16.12.0", "172.16.13.0", "172.155.43.9"]) == "172.0.0.0/8"), "Second Test"
assert (checkio(["172.16.12.0", "172.16.13.0", "172.155.43.9", "146.11.2.2"]) == "128.0.0.0/2"), "Third Test"
Feb. 9, 2021