Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Emily HK solution in Creative category for IP Network: Route Summarization by emilyhoughkovacs
def checkEqual(mylist):
if len(set([x[0] for x in mylist])) == 1:
if len(set([x[1] for x in mylist])) == 1:
if len(set([x[2] for x in mylist])) == 1:
return 3
return 2
return 1
return 0
def find_diff(mylist):
for x in range(9):
temp = []
for ip in mylist:
cur = ip[x]
temp.append(cur)
if len(set(temp))==1:
continue
else:
return x
def checkio(iplist):
numerical = []
binnums = []
for ip in iplist:
nums = [int(x) for x in ip.split('.')]
numerical.append(nums)
firstdiff = checkEqual(numerical)
for ip in numerical:
num = ip[firstdiff]
binary = '{0:08b}'.format(num)
binnums.append(binary)
diffloc = find_diff(binnums)
opposite = 8-diffloc
bindiff = binnums[0][0:diffloc]+'0'*opposite
numdiff = str(int(bindiff, 2))
masklength = firstdiff*8 + diffloc
mask = ''
if firstdiff == 0:
mask += numdiff
else:
for x in range(firstdiff):
mask += str(numerical[0][x])+'.'
mask+=numdiff
if firstdiff < 3:
for x in range(1, 4-firstdiff):
mask+='.0'
return mask+'/'+str(masklength)
#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"
March 21, 2016