Traffic System Simulation

Write a Python class TrafficSystem that simulates traffic lights at an intersection with methods to change states, detect collisions, and display the current state. The traffic lights can be in one of three states: “Red”, “Yellow”, “Green”.

Example 1:

Input: change_state("Green"), current_state()
Output: "Green"

Example 2:

Input: change_state("Red"), detect_collision(2), current_state()
Output: "Red"

Keep track of the current state and provide methods to change the state and detect collisions.

class TrafficSystem:
    def __init__(self):
        self.state = "Red"

    def change_state(self, new_state):
        self.state = new_state

    def detect_collision(self, cars):
        if cars > 1 and self.state == "Green":
            self.state = "Red"

    def current_state(self):
        return self.state

# Example usage
system = TrafficSystem()
system.change_state("Green")
print(system.current_state())  # Output: "Green"
system.detect_collision(2)
print(system.current_state())  # Output: "Red"

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!