Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for IP Network: Route Summarization by keromage
from functools import reduce
BIT = 8
IP_LENGTH = 4
def checkio(ip):
def compare_bits(bit_list_a, bit_list_b):
matched_bit = ["#"] * BIT
for i in range(BIT):
if bit_list_a[i] != bit_list_b[i]:
break
else:
matched_bit[i] = bit_list_a[i]
return matched_bit
def binarize(num):
return [i for i in "{:08b}".format(num)]
# convert dot address to list
# ['192.168.12.0', '192.168.13.0,,] -> [[192,168,12,0],[192,168,13,0],,]
ip_list = []
n_ip = len(ip)
for i in range(n_ip):
ip_list.append(ip[i].split("."))
# arrange from upper-byte
# [[192,192,192],[168,168,168],[12,13,14],[0,0,0]]
bytes = [[] * n_ip, [] * n_ip, [] * n_ip, [] * n_ip]
for j in range(n_ip):
for i in range(IP_LENGTH):
bytes[i].append(ip_list[j][i])
# Convert to binary and check if each bit matches.
# mark unmatched bits.
s_route = [] # summarized route
subnet = 0 # subnet
flag = 0
for j in range(IP_LENGTH):
data = [binarize(int(i)) for i in bytes[j]]
data = reduce(compare_bits, data)
bit_length = len(data) - data.count("#")
if flag == 1:
pass
else:
subnet += bit_length
if bit_length < BIT:
flag = 1
# Remove the marking and return the numerical value.
data = [i if i != "#" else "0" for i in data]
data = int("".join(data), 2)
s_route.append(data)
return "{}.{}.{}.{}/{}".format(
s_route[0], s_route[1], s_route[2], s_route[3], subnet
)
#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"
Jan. 3, 2022