简体   繁体   English

如何减少 if 语句并缩短代码?

[英]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.我不知道如何减少这些语句,因为每个语句在 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) R0915 (too-many-statements) 出现次数:1. [第 142 行] 语句过多 (24/20)

That looks like a py-lint warning, suggesting your code is trying to do too much in one routine.这看起来像一个 py-lint 警告,表明您的代码试图在一个例程中做太多事情。 Not really an error, but it does point to less-than-ideal coding practice.并不是真正的错误,但它确实指出了不太理想的编码实践。

You can reduce a few things in there.你可以在那里减少一些东西。

if x - 1 < 0:
    x_initial = x
else:
    x_initial = x - 1

can become可以变成

x_initial = x if x - 1 < 0 else x - 1

and so on for x_final, y_initial, and y_final.对于 x_final、y_initial 和 y_final,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM