mardi 29 octobre 2019

How can I reduce my if statements and shorten my code?

My code works, however, an error pops up saying there are too many statements.

I don't know how to reduce the statements because each one serves a purpose in the function.

def is_sink(elevation_map: List[List[int]], cell: List[int]) -> bool:
    """Return True if and only if cell exists in the elevation map
    elevation_map and cell is a sink.

    Precondition: elevation_map is a valid elevation map.
                  cell is a 2-element list.

    >>> is_sink(THREE_BY_THREE, [0, 5])
    False
    >>> is_sink(THREE_BY_THREE, [0, 2])
    True
    >>> is_sink(THREE_BY_THREE, [1, 1])
    False
    >>> is_sink(FOUR_BY_FOUR, [2, 3])
    True
    >>> is_sink(FOUR_BY_FOUR, [3, 2])
    True
    >>> is_sink(FOUR_BY_FOUR, [1, 3])
    False
    """    
    x = cell[0]
    y = cell[1]
    x_initial = 0
    x_final = 0
    y_initial = 0
    y_final = 0

    if x > len(elevation_map): 
        return False
    elif y > len(elevation_map[0]): 
        return False 
    if x - 1 < 0:
        x_initial = x
    else:
        x_initial = x - 1
    if x + 1 >= x:
        x_final = x
    else:
        x_final = x + 1
    if y - 1 < 0:
        y_initial = y
    else:
        y_initial = y - 1
    if y + 1 >= y:
        y_final = y
    else:
        y_final = y + 1
    validsink = True
    for i in range(x_initial, x_final + 1):
        for j in range(y_initial, y_final + 1):
            if elevation_map[i][j] < elevation_map[x][y]:
                validsink = False
    return validsink 

R0915 (too-many-statements) Number of occurrences: 1. [Line 142] Too many statements (24/20)

Aucun commentaire:

Enregistrer un commentaire