DEV Community

Vasanthakumari N
Vasanthakumari N

Posted on

Python Day 13: Solving Logical Problems Using While Loops

1. Two Trains – Finding Common Stations

Problem:

Two trains stop at regular intervals:

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

Find:

  1. The first common station where both trains stop.
  2. The last common station where both trains stop.
  3. All common stations where both trains stop.

Note: The total number of stations is unknown.

Understanding the Logic

Train 1 stops at:

3, 6, 9, 12, 15, 18, 21, 24, 27, 30...

Train 2 stops at:

5, 10, 15, 20, 25, 30, 35, 40, 45...

Common stations:

15, 30, 45, 60, 75, 90...

Both trains stop together at multiples of 15.

Since the total number of stations is unknown, we need a stopping limit to find the last common station. Let's assume the total number of stations is 100.

no = 1
first_station = True
last_station = 0

while no <= 100:
    if no % 3 == 0 and no % 5 == 0:

        if first_station:
            print("First station:", no)
            first_station = False
        else:
            print("Common station:", no)

        last_station = no

    no = no + 1

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

First station: 15
Common station: 30
Common station: 45
Common station: 60
Common station: 75
Common station: 90
Last station: 90
Enter fullscreen mode Exit fullscreen mode

2. Thief and Police Running Program

Problem:

A thief is running 30 feet ahead of a police officer.

  • Police officer runs 5 feet in each time interval.
  • Thief runs 2 feet in each time interval.

Find the distance at which the police officer catches the thief.

Step 1: Understand the Repeated Action

Initially:

police = 0
thief = 30

After every time interval:

police = police + 5
thief = thief + 2

We need to repeat these actions until the police officer catches the thief.

Step 2: Using a While Loop

police = 0
thief = 30

while police < thief:
    police = police + 5
    thief = thief + 2

print("Police catches thief at:", police)
Enter fullscreen mode Exit fullscreen mode
Output:

Police catches thief at: 50
Enter fullscreen mode Exit fullscreen mode

Top comments (0)