DEV Community

Athithya Sivasankarar
Athithya Sivasankarar

Posted on

Solving Train Station Problems Using Python While Loop

Problem Statement

We have two trains:

  • Train 1 stops at every 3rd station
  • Train 2 stops at every 5th station

We need to find:

  1. First station where both trains meet
  2. All stations where both trains meet
  3. Total count of common stations
  4. Last common station

We will check stations from 1 to 300.

1. First Station Where Both Trains Meet

station_no = 1

while station_no <= 300:

    if station_no % 3 == 0 and station_no % 5 == 0:
        print("First meeting station:", station_no)
        break

    station_no = station_no + 1
Enter fullscreen mode Exit fullscreen mode

Output

First meeting station: 15
Enter fullscreen mode Exit fullscreen mode

2. All Stations Where Both Trains Meet

station_no = 1

while station_no <= 300:

    if station_no % 3 == 0 and station_no % 5 == 0:
        print(station_no)

    station_no = station_no + 1
Enter fullscreen mode Exit fullscreen mode

Some outputs:

15
30
45
60
...
300
Enter fullscreen mode Exit fullscreen mode

3. Count of Common Stations

station_no = 1
count = 0

while station_no <= 300:

    if station_no % 3 == 0 and station_no % 5 == 0:
        count = count + 1

    station_no = station_no + 1

print("Total common stations:", count)
Enter fullscreen mode Exit fullscreen mode

4. Last Common Station

station_no = 1
last_station = 0

while station_no <= 300:

    if station_no % 3 == 0 and station_no % 5 == 0:
        last_station = station_no

    station_no = station_no + 1

print("Last common station:", last_station)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)