| Total Complexity | 12 |
| Total Lines | 59 |
| Duplicated Lines | 28.81 % |
| 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 | from itertools import combinations |
||
| 2 | |||
| 3 | |||
| 4 | def merge(island1, island2): |
||
| 5 | for i in island1: |
||
| 6 | for j in island2: |
||
| 7 | if abs(i[0] - j[0]) <= 1 and abs(i[1] - j[1]) <= 1: |
||
| 8 | return island1 + island2 |
||
| 9 | return [island1, island2] |
||
| 10 | |||
| 11 | |||
| 12 | def checkio(data): |
||
| 13 | lands = [] |
||
| 14 | for i, v in enumerate(data): |
||
| 15 | for col, value in enumerate(v): |
||
| 16 | if value == 1: |
||
| 17 | lands.append([(i, col)]) |
||
| 18 | merged = True |
||
| 19 | while merged: |
||
| 20 | merged = False |
||
| 21 | for i, j in combinations(lands, 2): |
||
| 22 | ret = merge(i, j) |
||
| 23 | if ret != [i, j]: |
||
| 24 | lands.remove(i) |
||
| 25 | lands.remove(j) |
||
| 26 | lands.append(ret) |
||
| 27 | merged = True |
||
| 28 | break |
||
| 29 | lands = [len(i) for i in lands] |
||
| 30 | return sorted(lands) |
||
| 31 | |||
| 32 | |||
| 33 | # These "asserts" using only for self-checking |
||
| 34 | # and not necessary for auto-testing |
||
| 35 | View Code Duplication | if __name__ == '__main__': |
|
|
|
|||
| 36 | assert checkio( |
||
| 37 | [ |
||
| 38 | [0, 0, 0, 0, 0], |
||
| 39 | [0, 0, 1, 1, 0], |
||
| 40 | [0, 0, 0, 1, 0], |
||
| 41 | [0, 1, 0, 0, 0], |
||
| 42 | [0, 0, 0, 0, 0], |
||
| 43 | ] |
||
| 44 | ) == [1, 3], "1st example" |
||
| 45 | assert checkio( |
||
| 46 | [[0, 0, 0, 0, 0], [0, 0, 1, 1, 0], [0, 0, 0, 1, 0], [0, 1, 1, 0, 0]] |
||
| 47 | ) == [5], "2nd example" |
||
| 48 | assert checkio( |
||
| 49 | [ |
||
| 50 | [0, 0, 0, 0, 0, 0], |
||
| 51 | [1, 0, 0, 1, 1, 1], |
||
| 52 | [1, 0, 0, 0, 0, 0], |
||
| 53 | [0, 0, 1, 1, 1, 0], |
||
| 54 | [0, 0, 0, 0, 0, 0], |
||
| 55 | [0, 1, 1, 1, 1, 0], |
||
| 56 | [0, 0, 0, 0, 0, 0], |
||
| 57 | ] |
||
| 58 | ) == [2, 3, 3, 4], "3rd example" |
||
| 59 |