Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Using ipaddress solution in Clear category for IP Network: Route Summarization by H0r4c3
import ipaddress
from itertools import takewhile
def checkio(data):
# convert the IP addresses to binary format
ip_bin = [''.join("{:08b}".format(int(i)) for i in ip.split('.')) for ip in data]
# find the common prefix
char_tuples = zip(*ip_bin)
prefix_tuples = takewhile(lambda x: all(x[0] == y for y in x), char_tuples)
common_prefix = ''.join(x[0] for x in prefix_tuples)
# calculate the subnet (number of common bits)
subnet = len(common_prefix)
# fill the uncommon part with 0
new_ip_bin = common_prefix.ljust(32, '0')
# convert the binary format to IP format
new_ip = str(ipaddress.ip_address(int(new_ip_bin, 2)))
# add the subnet to the new IP address
result = new_ip + '/' + str(subnet)
print(result)
return result
# 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. 1, 2022
Comments: