执行单独的、嵌套的if语句是否有效?

2024-05-16 18:35:07 发布

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

我正在研究以下问题:

You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.

我想出了以下代码:

def caught_speeding(speed, is_birthday):
    if is_birthday == True:
        if speed <= 65:
            return 0
        elif speed <= 85:
            return 1
        else:
            return 2
    else:
        if speed <= 60:
            return 0
        elif speed <= 80:
            return 1
        else:
            return 2

我觉得单独检查每一个都有点低效,或者可以吗?在


Tags: orandtheyouyourreturnifis
3条回答

我对你的代码没有问题。它是可读的和清晰的。在

如果你想少写几行,你可以这样做:

def caught_speeding(speed, is_birthday):
    adjustment = 5 if is_birthday else 0
    if speed <= 60 + adjustment:
        return 0
    elif speed <= 80 + adjustment:
        return 1
    else:
        return 2

你一定喜欢bisect模块。在

def caught_speeding(speed, is_birthday):
    l=[60,80]
    if is_birthday:
        speed-=5
    return bisect.bisect_left(l,speed)

您可以这样做:

def caught_speeding(speed, is_birthday):

    if is_birthday:
        speed = speed - 5

    if speed <= 60:
        return 0
    elif speed <= 80:
        return 1
    else:
        return 2

is_birthday == True表示你还没有得到布尔值;-)

相关问题 更多 >