DEV Community

Ajay
Ajay

Posted on

Python learning series | looping problems

1) Chocolate Wrapper Problem

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?

Flow Chart

Algorithm

  1. Initial total_amount = 100 , total chocolate = 0 , wrapper = 0 .
  2. Check whether total_ amount is greather than equal to 5.
  3. if True --->
    • wrapper = wrapper + 1
    • total_chocolate = total_chocolate + 1
    • total_amount = total_amount - 5
  4. Check wheather wrapper >= 3
  5. if Ture --->

    • total_chocolate = total_chocolate + 1
    • wrapper = wrapper - 3 + 1
  6. Repeat the 3 and 6 untill the total_amount become less then 5 .

  7. print the total chocolate

total_amount = 2025
total_chocolate = 0
wrapper = 0
while total_amount >= 5 :
    wrapper = wrapper + 1
    total_chocolate = total_chocolate + 1
    total_amount = total_amount - 5

    if wrapper >= 3:
        total_chocolate = total_chocolate + 1
        wrapper = wrapper - 3 + 1

print("Total_chocolate : "total_chocolate)
Enter fullscreen mode Exit fullscreen mode

output

Total_chocolate : 29
Enter fullscreen mode Exit fullscreen mode

2) Chapathi Story

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?

Flow Chart

Algorithm

  1. Initial chapathi = 8 and count = 0
  2. Check whether count less than < 3
  3. if yes --->
    • chapathi = chapathi // 2 * 3
    • count = count + 1

4.Repeat untill it count greater than 3.
5.print chapathi it displayes total chapathi

count = 0
chapathi = 8


while count < 3 :   # breakfast , lunch ,  dinner
    chapathi = chapathi // 2 * 3   # 1/3 is he had ate , 2/3 is had remaining for one count(breakfast or lunch or dinner)
    count = count + 1

print("Total chapathi : ",chapathi)

Enter fullscreen mode Exit fullscreen mode

Output

Total chapathi :  27
Enter fullscreen mode Exit fullscreen mode

Top comments (0)