1

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

7 Comments

what is this syntax called: return 0 ... else 1 ... else 2 ... else 0 I've never seen this before, specifically the else parts of the line
Doesn't answer the question and is pretty long. Do you think a speed of 80.9 shall get unpunished?
@kelly-bundy You're right, the solution is a little bit long. Also, a speed of 80.9 receives a result of only 1 because that's the rule it has to obey.
"little bit" as in the return expression is about three times as long as necessary :-). I meant 80.9 not on the birthday. You return 0 then, not 1. That's why I said unpunished.
@kelly-bundy Ok, I completely forgot about the birthday component. Thanks for remembering. I will update the answer
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.