DEV Community

Saravanan Cn
Saravanan Cn

Posted on

Python while Loop Practise:Chocolate wrappers and Chapathi Story

1.Chocolate wrapper Problem
Problem Statement:
You have Rs. 100 /- One chocolate costs Rs. 5. Every time you buy a chocolate, you get one wrapper. You can exchange 3 wrappers for 1 additional chocolate. What is the maximum number of chocolates you can have with Rs. 100?
Solution:
money = 100
cost = 5

chocolates = money//cost
wrappers = chocolates

Initially:
100/5 = 20 chocolates.
20 chocolates gives 20 wrappers.

Program using while loop:

money = 100
cost = 5

chocolates = money // cost
wrappers = chocolates

while wrappers >= 3:
    extra_chocolates = wrappers // 3

    chocolates = chocolates + extra_chocolates

    wrappers = (wrappers % 3) + extra_chocolates

print("Total chocolates:", chocolates)

Output:
Total chocolates:29
Enter fullscreen mode Exit fullscreen mode

2.Chapathi story

Problem Statement:

There is one person called Viyan. He is a Software Engineer. He employs a maid for cooking. One day, the maid prepared n number of chapathis and kept in a hot box. Viyan ate those chapathis and the count is as follows:
* For Morning breakfast, he completed 1/3 number of chapathis in the hot box.
* For Lunch, He had 1/3 of what was there in the hot box.
* For Dinner, again he took and ate 1/3 number of chapathis present in the box.

The next day morning, When the maid checked the number of chapathis remaining, it was 8. What was the number of chapathis, She made - in total?

Solution:
Vijayan eats 1/3 of the chapathis.

One whole =1.

1-1/3 = 2/3.

8*3/2

2/3 is reversed 3/2 we are working backwards to find the original number of chapathis.


_
Program using while loop:_

chapathis = 8
meals = 3

while meals > 0:
    chapathis = chapathis * 3 // 2
    meals = meals - 1

print("Original chapathis:", chapathis)

Output:
Total chocolates: 27
Enter fullscreen mode Exit fullscreen mode
  • I also learned that sometimes solving a problem backwards make it easier to find the answer.
  • I continue to improve my python programming and problem-solving skills one at a time.

Top comments (1)

Collapse
 
payilagam_135383b867ea296 profile image
Payilagam •

Last two lines are very nice.