LeetCode 3894. Traffic Signal Color Chapter 1
CHAPTER 1 OF 1

3894. Traffic Signal Color

We work through an if/elif ladder, then tighten the range checks using Python's chained-comparison syntax. The `a <= x < b` form replaces clumsy boolean ANDs anywhere you have ranges.

Problem

You are given an integer timer representing the remaining time (in seconds) on a traffic signal.

The signal follows these rules:

  • If timer == 0, the signal is "Green".
  • If timer == 30, the signal is "Orange".
  • If 30 < timer <= 90, the signal is "Red".

Return the current state of the signal. If none of the above conditions are met, return "Invalid".

Constraints:

  • 0 <= timer <= 1000

Examples:

  • timer = 60"Red". 30 < 60 <= 90 so the signal is red.
  • timer = 5"Invalid". 5 doesn't satisfy any of the given conditions.

Walkthrough

If statements

In this problem we have to condition our output based on what the input is. What they've done here is included a range of conditions to make sure that you cater for each one: - Exact equality for the 0 and 30 check - Different inequalities: exclusive for the 30 and inclusive for the 90. - Values that don't fall to any condition

The simplest way would be to do this with an if/elif/else block. The main tricky bit here is for the Red condition, where we need two things to be true together timer > 30 and timer <= 90 to ensure it's within the range. We're told that timer is an integer, so that means it must be a whole number. You could also write this as timer >= 31 if you prefer to just use inclusive inequalities. Finally, at the end for the Invalid output you can either do a fall through and just return it at the end, or you can put it in an else block. They're functionally the same.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def trafficSignal(self, timer: int) -> str:
    if timer == 0:
      return "Green"
    elif timer == 30:
      return "Orange"
    elif timer > 30 and timer <= 90:
      return "Red"
    # If no conditions have been satisfied it's invalid.
    return "Invalid"
Submission result If statements submission result on LeetCode

Double inequality

We can actually simplify this a bit further to make it more readable. Python lets you chain inequalities together, so we can collapse the timer > 30 and timer <= 90 check into a single 30 < timer <= 90. I think this makes the code more readable:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def trafficSignal(self, timer: int) -> str:
    if timer == 0:
      return "Green"
    elif timer == 30:
      return "Orange"
    elif 30 < timer <= 90:
      return "Red"
    # If no conditions have been satisfied it's invalid.
    return "Invalid"
Submission result Double inequality submission result on LeetCode