Aug-14-2021, 08:04 PM
(Aug-14-2021, 07:09 AM)perfringo Wrote: It is always good to have names. This makes comprehending much more easier for humans (computer doesn't care :-).Key here was that you were thinking of programming, not thinking about the problem. The problem was clearly stated: compute the tip on the meal plus tax. Once you express that in English (or French), the answer is obvious. Don't get caught in the syntax trap. Work it out in your native language first, then write down how to do it so a seven-year-old could figure it out (well, maybe an 8-year-old). If you can't explain it to a small child, you can't program it (small children are much, much smarter than computers). That's one of the secrets of successful programming.
So you first iteration could become (EDIT: rates are changed compared to your example):
>>> meal = 8 >>> tax_rate = 0.15 >>> tip_rate = 0.13 >>> first = meal + (meal * tax_rate) + (meal * tip_rate) >>> print(first) 10.239999999999998
Simple enough. Second iteration requires that tip would be calculated on amount of meal with tax amount. So it would be:
>>> second = meal + (meal * tax_rate) + ((meal + (meal * tax_rate)) * tip_rate) >>> print(second) 10.395999999999999As you can observe that this is quite complicated and we calculatedmeal * tax_rate
twice. Modern Python enables us to use assignment expression to avoid this. We calculate tax amount and give it a name and then use this name in next calcuation. So it can be written:
>>> second = meal + (tax_amount := meal * tax_rate) + ((meal + tax_amount) * tip_rate) >>> print(second) 10.395999999999999And... Please use Python code tags!
I was working with my intern a couple days ago. I wanted to leave him with a project to do a particular computation. We wrote about 30 lines of comments explaining what the algorithm was and how it had to work. His programming will be trivial now. Because everything is written down in simple English (our shared language).