ip_network_route_summarization.checkio()   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nop 1
dl 0
loc 16
rs 9.85
c 0
b 0
f 0
1
def convert_bin(ip):
2
    # convert ip to 32bits bin
3
    ret = ''
4
    for i in ip.split('.'):
5
        ret += '{:>08}'.format(bin(int(i))[2:])
6
    return ret
7
8
9
def convert_dec(ip):
10
    return '.'.join([str(int(ip[i : i + 8], 2)) for i in range(0, 32, 8)])
11
12
13
def checkio(data):
14
    bin_data = []
15
    for i in data:
16
        bin_data.append(convert_bin(i))
17
18
    # find the longest match for all bin string
19
    mask_length = 0
20
    while mask_length <= 32:
21
        if len(set([i[mask_length] for i in bin_data])) == 1:
22
            mask_length += 1
23
        else:
24
            break
25
26
    # 'cut off' the unmasked part
27
    summaried_bin = bin_data[0][:mask_length] + '0' * (32 - mask_length)
28
    return convert_dec(summaried_bin) + '/' + str(mask_length)
29
30
31
# These "asserts" using only for self-checking and not necessary for
32
# auto-testing
33 View Code Duplication
if __name__ == '__main__':  # pragma: no cover
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
34
    assert (
35
        checkio(["172.16.12.0", "172.16.13.0", "172.16.14.0", "172.16.15.0"])
36
        == "172.16.12.0/22"
37
    ), "First Test"
38
    assert (
39
        checkio(["172.16.12.0", "172.16.13.0", "172.155.43.9"]) == "172.0.0.0/8"
40
    ), "Second Test"
41
    assert (
42
        checkio(["172.16.12.0", "172.16.13.0", "172.155.43.9", "146.11.2.2"])
43
        == "128.0.0.0/2"
44
    ), "Third Test"
45