2011-02-13 67 views
0

我正在以下问题:执行个别嵌套if语句是否有效?

您驾驶的是有点太快了,和警察阻止你。编写代码来计算结果,编码为一个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 

我觉得单独检查每一个有点低效,还是确定?

+2

不要做`如果东西==真:` - `如果东西:`足够了。 – 2011-02-13 01:28:13

回答

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

你一定喜欢bisect模块。

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意味着你没有完全得到尚布尔;-)

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