DEV Community

sridhar n
sridhar n

Posted on

Python Day 12 – Story Problems With Loops (Daughter, Frog and Saint)

Today's problems were little stories. Way more fun than "print 1 to 10".

1. The daughter's vacation money

Her plan: Rs. 5 every day for 5 days.
Dad's plan: Day 1 → Rs. 1, Day 2 → Rs. 2 ... Day 5 → Rs. 5.

Her plan:

box = 0
day = 1
while day <= 5:
    box = box + 5
    day = day + 1
print(box)   # 25
Enter fullscreen mode Exit fullscreen mode

Dad's plan:

box = 0
day = 1
while day <= 5:
    box = box + day
    day = day + 1
print(box)   # 15
Enter fullscreen mode Exit fullscreen mode

The only difference is + 5 vs + day. Change 5 to 10 for a 10-day trip: 50 vs 55. Now dad's plan wins!

Sum and product of the first n numbers

total = 0
no = 1
while no <= 10:
    total = total + no
    no = no + 1
print(total)   # 55
Enter fullscreen mode Exit fullscreen mode

For multiplication, start total at 1, not 0:

total = 1
no = 1
while no <= 5:
    total = total * no
    no = no + 1
print(total)   # 120
Enter fullscreen mode Exit fullscreen mode

Why? 0 is the additive identity (adding 0 changes nothing), and 1 is the multiplicative identity (multiplying by 1 changes nothing). Start with 0 and the product stays 0 forever.

2. Frog in a 60 ft well

Climbs 2 ft by day, slips 0.5 ft at night. If it reaches the top during the day, it's out.

position = 0
day = 0
while True:
    day = day + 1
    position = position + 2      # day climb
    if position >= 60:
        break                    # escaped, no slipping
    position = position - 0.5    # night slip

print("Frog escapes on day", day)   # 40
Enter fullscreen mode Exit fullscreen mode

My first attempt gave 39, because I applied the night slip even on the last day. The note in the question ("doesn't slip back once it's out") is the whole trick.

3. The saint's flower basket

He visits 7 temples and gives half his flowers at each one. He ends with 1 flower. How many did he start with?

The trick is to work backwards: doubling undoes halving.

count = 1
temples = 7
while temples > 0:
    count = count * 2
    temples = temples - 1
print(count)   # 128
Enter fullscreen mode Exit fullscreen mode

Lesson for today: sometimes the easiest direction to solve a problem is backwards.

Top comments (0)