Test Setup Failed
Push — master ( 9c636e...0d417c )
by Ken M.
48s
created

convert_dec()   A

Complexity

Conditions 2

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 2
rs 10
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
if __name__ == '__main__':  # pragma: no cover
34
    assert (checkio(["172.16.12.0", "172.16.13.0", "172.16.14.0",
35
                     "172.16.15.0"]) == "172.16.12.0/22"), "First Test"
36
    assert (checkio(["172.16.12.0", "172.16.13.0", "172.155.43.9"])
37
            == "172.0.0.0/8"), "Second Test"
38
    assert (checkio(["172.16.12.0", "172.16.13.0", "172.155.43.9",
39
                     "146.11.2.2"]) == "128.0.0.0/2"), "Third Test"
40