| Total Complexity | 7 |
| Total Lines | 45 |
| Duplicated Lines | 26.67 % |
| Changes | 0 | ||
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 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 |
|
|
|
|||
| 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 |