DEV Community

sridhar n
sridhar n

Posted on

Python Day 13 – Police vs Thief, Two Trains and LCM

The problems got harder today. We solved two in class.

Police chasing a thief

The thief starts 30 ft ahead and runs 2 ft per step. The police run 5 ft per step. Where does the police catch him?

Micro version first:

police = 0
thief = 30
police = police + 5
thief = thief + 2
# ...and so on
Enter fullscreen mode Exit fullscreen mode

Then the loop:

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

print(police)   # 50
Enter fullscreen mode Exit fullscreen mode

Small but important: I first wrote while police != thief. That only works if they land on exactly the same spot. With other speeds the police could jump past the thief and the loop would never stop. Using < is safer.

Two trains (LCM in disguise)

Train 1 stops at every 3rd station, Train 2 at every 5th. Which stations do both stop at?

Multiples of 3: 3 6 9 12 15 18 21 24 27 30
Multiples of 5: 5 10 15 20 25 30

Common ones: 15, 30, ... The smallest one is the LCM (Least Common Multiple) = 15.

no = 1
last_station = 0
first_station = True

while no <= 100:
    if no % 3 == 0 and no % 5 == 0:
        if first_station:
            print('First Station is', no)
            first_station = False
        else:
            print('Common Station is', no)
        last_station = no
    no = no + 1

print('Last Station is', last_station)
Enter fullscreen mode Exit fullscreen mode

Since the total number of stations is unknown, I assumed 100.

The first_station flag was a nice trick: a variable that "remembers" whether we've already found the first one. (Ground rule #5: introduce a variable when you need one.)

One more thing I learned:

  • if checks a condition once
  • while checks it again and again

Other problems

  • Tenali Raman and the guards (halving 1024 lashes)
  • Dividing N tiles into equal groups (factors)
  • Special lock number (prime check)
  • First 5 VIP numbers (first 5 primes: 2, 3, 5, 7, 11)
  • Special cards from 1 to 20 (primes in a range)
  • Chocolate wrapper problem
  • The chapathi story (work backwards again!)

Something the trainer said that stuck

Use AI tools if you want, but verify the output and understand it. Easy programs and hard programs both need practice. And like Sachin, the practice is what makes the difference.

Top comments (0)