berserk_rook.find_connect_rook()   F
last analyzed

Complexity

Conditions 15

Size

Total Lines 32
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 30
nop 2
dl 0
loc 32
rs 2.9998
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like berserk_rook.find_connect_rook() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
def find_connect_rook(berserker, enemies):
2
    col, row = list(berserker)
3
    result = []
4
    # same row
5
    bigger = True
6
    smaller = True
7
    for i in range(8):
8
        if bigger and int(row) + i <= 8:
9
            pseudo_enemy = col + str(int(row) + i)
10
            if pseudo_enemy in enemies:
11
                result.append(pseudo_enemy)
12
                bigger = False
13
        if smaller and int(row) - i >= 1:
14
            pseudo_enemy = col + str(int(row) - i)
15
            if pseudo_enemy in enemies:
16
                result.append(pseudo_enemy)
17
                smaller = False
18
    # same col
19
    bigger = True
20
    smaller = True
21
    for i in range(8):
22
        if bigger and chr(ord(col) + i) <= 'h':
23
            pseudo_enemy = chr(ord(col) + i) + row
24
            if pseudo_enemy in enemies:
25
                result.append(pseudo_enemy)
26
                bigger = False
27
        if smaller and chr(ord(col) - i) >= 'a':
28
            pseudo_enemy = chr(ord(col) - i) + row
29
            if pseudo_enemy in enemies:
30
                result.append(pseudo_enemy)
31
                smaller = False
32
    return result
33
34
35
def berserk_rook(berserker, enemies):
36
    connected_enemies = find_connect_rook(berserker, enemies)
37
    if not connected_enemies:
38
        return 0
39
    new_status = [(i, [j for j in enemies if j != i]) for i in connected_enemies]
40
    aaa = [berserk_rook(*i) for i in new_status]
41
    result = max(aaa)
42
    return 1 + result
43
44
45
if __name__ == '__main__':
46
    # These "asserts" using only for self-checking and not necessary for
47
    # auto-testing
48
    assert (
49
        berserk_rook(u'd3', {u'd6', u'b6', u'c8', u'g4', u'b8', u'g6'}) == 5
50
    ), "one path"
51
    assert (
52
        berserk_rook(u'a2', {u'f6', u'f2', u'a6', u'f8', u'h8', u'h6'}) == 6
53
    ), "several paths"
54
    assert (
55
        berserk_rook(u'a2', {u'f6', u'f8', u'f2', u'a6', u'h6'}) == 4
56
    ), "Don't jump through"
57