Reputation: 11
The question, my answer, and the output is screenshotted here
Constraints:
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.
My Code:
def caught_speeding(speed, is_birthday):
if speed > 80 or (speed > 85 and is_birthday):
return 2
return int((60 < speed <= 80) or (65 < speed <= 85 and is_birthday))
caught_speeding(65, True)
gives 1 but should be 0
caught_speeding(85, True)
gives 2 but should be 1
the other tests are ok. When I trace the code I cant seem to find the error
Upvotes: 1
Views: 55
Reputation: 5223
You can come up with a one-liner solution using the following logic, subtracting 5 from speed
when is_birthday
parameter gets a True
value:
def caught_speeding(speed, is_birthday):
if is_birthday:
speed -= 5
return 0 if speed < 60 else 1 if speed <= 80 and speed >= 61 else 2 if speed >= 81 else 0
print(caught_speeding(81, 0))
print(caught_speeding(65, True))
print(caught_speeding(85, True))
Output:
2
0
1
Upvotes: 0
Reputation: 24052
For caught_speeding(65, True)
, the first condition is false so it falls through to the return
statement. In that case, (60 < speed <= 80)
is true, since 65 falls within that range. The other condition doesn't matter since it's joined with an or
, so it's effectively doing return int(True)
which is 1
.
For caught_speeding(85, True)
, the speed > 80
condition is true, since 85 is greater than 80. Again, the other condition doesn't matter since it's joined with an or
, so it executes the return 2
statement.
Upvotes: 1