如果返回的代码太复杂,如何修复太多的错误

2024-09-28 22:51:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有太多的if语句,我很难理解字典系统。你知道吗

这看起来很容易解决,但我做的每一件事都会让事情变得更糟。你知道吗

    """
    Find the place where the person was born.

    Possible locations are following: Kuressaare, Tartu, Tallinn, Kohtla-Järve, Narva, Pärnu,
    Paide, Rakvere, Valga, Viljandi, Võru and undefined. Lastly if the number is incorrect the function must return
    the following 'Wrong input!'
    :param birth_number: int
    :return: str
    """
    return 
    if not is_valid_birth_number(birth_number):
        return "Wrong input!"
    if 10 >= birth_number >= 1:
        return "Kuressaare"
    elif 20 >= birth_number >= 11:
        return "Tartu"
    elif 220 >= birth_number >= 21:
        return "Tallinn"
    elif 270 >= birth_number >= 221:
        return "Kohtla-Järve"
    elif 370 >= birth_number >= 271:
        return "Tartu"
    elif 420 >= birth_number >= 371:
        return "Narva"
    elif 470 >= birth_number >= 421:
        return "Pärnu"
    elif 490 >= birth_number >= 471:
        return "Tallinn"
    elif 520 >= birth_number >= 491:
        return "Paide"
    elif 570 >= birth_number >= 521:
        return "Rakvere"
    elif 600 >= birth_number >= 571:
        return "Valga"
    elif 650 >= birth_number >= 601:
        return "Viljandi"
    elif 710 >= birth_number >= 651:
        return "Võru"
    elif 999 >= birth_number >= 711:
        return "undefined"

需要消除idcode.py:149:1: C901 'get_birth_place' is too complex (16)错误。你知道吗


Tags: thenumberreturnifisplacefollowingbirth
3条回答

^{}为例。你知道吗

import bisect

locations = {
    1: 'Kuressaare',
    2: 'Tartu',
    3: 'Tallinn',
    4: 'Kohtla-Järve',
    5: 'Tartu'
}

birth_number_levels = [1, 11, 21, 221, 271, 371]
position = bisect.bisect(birth_number_levels, birth_number)
return locations[position]

我更喜欢像@Barmar那样把数据放在一起。这导致:

import bisect

locations = [
    (10, 'Kuressaare'),
    (20, 'Tartu'),
    (220, 'Tallinn'),
    (270, 'Kohtla-Järve'),
    (370, 'Tartu')
]
birth_number_levels = [location[0] for location in locations]
position = bisect.bisect_left(birth_number_levels, birth_number)
return locations[position][1]

我会使用字典,它包含键作为范围,值是位置的名称。 然后遍历它,检查给定的birth_number是否在键中。你知道吗

基本上:

loc_dict = {
    range(1, 11): "Kuressaare",
    range(11, 21): "Tartu",
    etc...
}

for loc_range, loc_name in loc_dict.items():
    if birth_number in loc_range:
        return loc_name

我认为这是一个很清楚的处理方法。你知道吗

使用将每个范围的结尾映射到返回值的列表。你知道吗

if not is_valid_birth_number(birth_number):
    return "Wrong input!"

locations = [(10, "Kuressaare"), (220, "Tartu"), (270, "Tallinn"), ...]
for limit, loc in locations:
    if birth_number <= limit:
        return loc

你不需要每个范围的开始和结束,因为它们是有序的。仅仅是范围的尽头就足够了。你知道吗

相关问题 更多 >