跳到正文
DEV Community· sridhar n·· 5 天前AI 評分25

Python Day 13:警察追小偷、雙列車與最小公倍數

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

AI 導讀

Python Day 13 練習以迴圈解決警察追小偷及雙列車停站問題:警察每步跑 5 ft、小偷每步跑 2 ft 並領先 30 ft,程式算出警察在 50 ft 處追上小偷。兩列車分別每隔 3 站和 5 站停靠,共同停靠站包括 15、30,最小公倍數是 15;文章亦提醒使用 AI 工具後要核實輸出並理解內容。

正文

sridhar n

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

Then the loop:

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

print(police)   # 50

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)

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.

來源:DEV Community · dev.to