开发者

Is it efficient to perform individual, nested if statements?

I'm working on the following problem:

You are driving a little too fast, and a police officer stops you. Write code to compute the 开发者_JS百科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.

I came up with the following code:

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

I feel like checking each one individually is a bit inefficient, or is it ok?


You gotta love the bisect module.

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


I have no problems with your code. It is readable and clear.

If you want to go for less lines then you can do something like this:

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


You can do this:

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

Doing is_birthday == True means you didn't quite get booleans yet ;-)


Check this one. It is optimised:

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


Assuming that speed is an integer, and that efficiency means speed of running, not speed of understanding:

>>> 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
>>>


def caught_speeding(speed, is_birthday):
    speed -= 5 * is_birthday
    return 0 if speed < 61 else 2 if speed > 80 else 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜