DEV Community

Cover image for python looping part[4]
Keerthana M
Keerthana M

Posted on

python looping part[4]

12)Tenali Raman and the Palace Guards
Tenali Raman wishes to meet the King. Before reaching the royal court, he has to pass through many palace gates. A guard is posted at each gate.
Every guard demands a share of whatever reward Tenali Raman receives from the King. Tenali Raman agrees and promises:
"I will give you half of whatever reward I receive from the King."
All the guards allow him to enter. After meeting the King, Tenali Raman receives a reward of 1024 lashes.
Keeping his promise, Tenali Raman shares his reward with the guards. At each gate, he gives half of the lashes he still has to receive to the guard at that gate and proceeds to the next gate.
Write a program to determine:

1.How many lashes each guard receives.
2.How many Guards are there if Tenali Raman gets only one lash.

guards = 0
lashes = 1024
while lashes > 1:
    lashes //= 2
    print(lashes)
    # guards += 1
    guards=guards+1
print('Guards Count is', guards)
Enter fullscreen mode Exit fullscreen mode

Output:
512
256
128
64
32
16
8
4
2
1

Guards Count is 10

13.The Thief and Police running program....

police, thief = 0, 40
step = 0
while thief > police:
    police = police + 5
    thief = thief + 2
    step+=1
print(police)
print(step)
Enter fullscreen mode Exit fullscreen mode

Output:
70
14

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 = 0
first_station = True

while station <= 80:
    if station % 3 == 0 and station % 5 == 0:
        if first_station:
            print("First Station is:", station)    # first station 
            first_station = False
        print(station)                            # all station

        last_station = station

    station += 1

print("Last Common Station is:", last_station)     #last station
Enter fullscreen mode Exit fullscreen mode

#1-% Operator
#2-and Operator
#3-Overlapped Value for last station
#4-Printing the last overlapped value outside the loop.
#5-Printing value inside loop - will give us all the values.

OUTPUT:

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

Top comments (0)