【发布时间】:2018-05-15 12:21:07
【问题描述】:
我不确定为什么此代码在一些输入中失败(来自 CodingBat,问题链接:Exercise Link)。问题详情如下,我可以用if elif 语句来做这个问题,但我想使用字典。另外,我读到不建议从字典中获取键值,如下所示。但是,如果可以指出以下程序中的问题,我将不胜感激。
你开得太快了,警察拦住了你。编写代码来计算结果,编码为 int 值:0=无票,1=小票,2=大票。如果速度小于等于 60,则结果为 0。如果速度介于 61 和 80 之间,则结果为 1。如果速度大于或等于 81,则结果为 2。除非是你的生日——那天,你的在所有情况下,速度都可以提高 5 倍。
- caught_speeding(60, False) → 0
- caught_speeding(65, False) → 1
- caught_speeding(65, True) → 0
def caught_speeding(speed, is_birthday): Bir_dict = {0:speed<=60,1:61<=speed<=80,2:speed>=81} NoBir_dict = {0:speed<=65,1:66<=speed<=85,2:speed>=86} def getKey(dict,value): return [key for key in dict.keys() if (dict[key] == value)] if is_birthday: out1=getKey(Bir_dict,True) return out1[0] else: out2=getKey(NoBir_dict,True) return out2[0]
程序失败了
caught_speeding(65, False)
caught_speeding(65, True)
并为
工作caught_speeding(70, False)
caught_speeding(75, False)
caught_speeding(75, True)
caught_speeding(40, False)
caught_speeding(40, True)
caught_speeding(90, False)
caught_speeding(60, False)
caught_speeding(80, False)
【问题讨论】:
标签: python dictionary