I am not sure why this code is failing for a few inputs (from CodingBat, link to question : Exercise Link). Problem details are below, I could probably do this question with if elif statements, but I want to use dictionaries. Also, I have read that it is not recommended to fetch key values from a dictionary as used below. But I will appreciate it if the issue in below program can be pointed out.
You are driving a little too fast, and a police officer stops you. Write code to compute the 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.
- 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]
The programs is failing for
caught_speeding(65, False)
caught_speeding(65, True)
And working for
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)