calculate_islands.merge()   A
last analyzed

Complexity

Conditions 5

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 6
nop 2
dl 0
loc 6
rs 9.3333
c 0
b 0
f 0
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__':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
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