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

问题描述 投票:0回答:6

我正在研究以下问题。

你开得有点快,一个警察拦住了你。写代码来计算结果,编码为一个int值:0=无罚单,1=小罚单,2=大罚单。如果车速在60以内,结果为0,如果车速在61到80(含)之间,结果为1,如果车速在81以上,结果为2,除非是你的生日--那天,你的车速在任何情况下都可以提高5。

我想出了下面的代码。

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

我觉得每个人都单独检查有点效率低,还是可以的?

python boolean-logic
6个回答
1
投票

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

如果你想减少行数,那么你可以这样做。

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

3
投票

你一定要喜欢 一分为二 模块。

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

1
投票

你可以这样做。

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 意味着你还没有完全掌握booleans;-)


1
投票

检查这个。它是经过优化的。

def caught_speeding(speed, is_birthday):
 if speed in range(0,66 if is_birthday else 61):
   return 0
 elif speed in range(0,86 if is_birthday else 81):
   return 1
 return 2

0
投票

假设速度是一个整数,而且效率是指运行的速度,而不是理解的速度。

>>> def t(speed, is_birthday):
...     speed -= 5 * is_birthday
...     return speed // 61 + speed // 81
...
>>> for s in xrange(58, 87):
...     print s, t(s, False), t(s, True)
...
58 0 0
59 0 0
60 0 0
61 1 0
62 1 0
63 1 0
64 1 0
65 1 0
66 1 1
67 1 1
68 1 1
69 1 1
70 1 1
71 1 1
72 1 1
73 1 1
74 1 1
75 1 1
76 1 1
77 1 1
78 1 1
79 1 1
80 1 1
81 2 1
82 2 1
83 2 1
84 2 1
85 2 1
86 2 2
>>>

0
投票
def caught_speeding(speed, is_birthday):
    speed -= 5 * is_birthday
    return 0 if speed < 61 else 2 if speed > 80 else 1
© www.soinside.com 2019 - 2024. All rights reserved.