Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Verbose, perhaps too many intermediate variables, but clear solution in Clear category for IP Network: Route Summarization by kkkkk
import textwrap
def checkio(data):
"""Return the summary route for the input IP addresses."""
# Convert the addresses to strings of binary digits.
binary_ipaddrs = []
for ip_str in data:
binary_ipaddrs.append(
''.join(f'{int(x):08b}' for x in ip_str.split('.')))
# Starting from the left, find the number of bits that are common
# to all addresses.
min_common_bits = 32
for ipaddr in binary_ipaddrs[1:]:
cnt = 0
while ipaddr[cnt] == binary_ipaddrs[0][cnt]:
cnt += 1
if cnt < min_common_bits:
min_common_bits = cnt
# Create the summary address by replacing the non-common bits with 0.
summary_addr = binary_ipaddrs[0][:min_common_bits] + \
'0' * (32 - min_common_bits)
# Convert the resulting number back into 4 octets, then add a slash
# and the number of common bits.
octets = '.'.join(str(int(octet, 2))
for octet in textwrap.wrap(summary_addr, 8))
return f'{octets}/{min_common_bits}'
Nov. 18, 2019
Comments: