DEV Community

Kiruthiga S
Kiruthiga S

Posted on Edited on

Python

14)Two trains stop at regular intervals:
Train 1 stops at every 3rd station.
Train 2 stops at every 5th station.
Find:
The first common station where both trains stop.
The last common station where both trains stop.
All common stations where both trains stop.

Note: Total Number of Stations are unknown.

station = 1
last_station = station
first_station = True
while station <= 100:
    if station % 3 == 0 and station % 5 == 0:
        if first_station == True:
            print('First Station is: ', station)
            first_station = False
        else:
            print(station) 
        last_station = station   
    station+=1
print("Last Common Station is", last_station)
Enter fullscreen mode Exit fullscreen mode

Output:First Station is: 15
30
45
60
75
90
Last Common Station is 90

common = []
station= 1

while station <= 100:
    if station % 3 == 0 and station % 5 == 0:
    #   common += [station]
        common =common + [station]
    station += 1

print("First common station:", common[0])
print("Last common station:", common[-1])
print("All common stations:", common)

Enter fullscreen mode Exit fullscreen mode

Output:First common station: 15
Last common station: 90
All common stations: [15, 30, 45, 60, 75, 90]

Top comments (0)