我不确定为什么这段代码失败了一些输入(来自CodingBat,链接到问题:Exercise Link)。问题详情如下,我可以用if elif
语句来解决这个问题,但我想使用字典。此外,我已经读过,建议不要从字典中获取键值,如下所示。但如果可以指出以下方案中的问题,我将不胜感激。
你驾驶的速度有点太快,一名警察阻止你。编写代码来计算结果,编码为int值:0 =没有票,1 =小票,2 =大票。如果速度为60或更低,则结果为0.如果速度在61和80之间,则结果为1.如果速度为81或更高,则结果为2.除非是您的生日 - 在那一天,您的在所有情况下,速度可以高出5个。
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)
答案 0 :(得分:2)
看起来像是混合了Bir_dict
和NoBir_dict
。你能试试下面的代码吗?
def caught_speeding(speed, is_birthday):
Bir_dict = {0:speed<=65,1:66<=speed<=85,2:speed>=86}
NoBir_dict = {0:speed<=60,1:61<=speed<=80,2:speed>=81}
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]
尽管它有效,但我可以建议使用字典的替代方法:票证定义不会相互干扰,换句话说,字典中只能有一个True
语句。因此,您可以将代码修改为:
def caught_speeding(speed, is_birthday):
Bir_dict = {0:speed<=65,1:66<=speed<=85,2:speed>=86}
NoBir_dict = {0:speed<=60,1:61<=speed<=80,2:speed>=81}
def getKey(dict):
return [key for key in dict.keys() if (dict[key] == True)]
if is_birthday:
out1=getKey(Bir_dict)
return out1[0]
else:
out2=getKey(NoBir_dict)
return out2[0]
答案 1 :(得分:1)
问题不会认为生日词典具有更高的可用值吗?
如果是我的生日,我要去65岁: 我不指望没有票。 但是,如果您生成字典并打印它们,您可以看到情况并非如此:
def caught_speeding(speed, is_birthday):
Bir_dict = {0:speed<=60,1:61<=speed<=80,2:speed>=81}
print Bir_dict
NoBir_dict = {0:speed<=65,1:66<=speed<=85,2:speed>=86}
print NoBir_dict
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]
输出:
{0: False, 1: True, 2: False}
{0: True, 1: False, 2: False}
0
{0: False, 1: True, 2: False}
{0: True, 1: False, 2: False}
1
您只需在字典对象中交叉值