A University is testing a new fertilizer. They are interested in how long the fertilizer may be kept before its effectiveness is lost. They have done some calculations that indicate the fertilizer loses 6% of its potency every month. Design a Python algorithm that finds how many months it takes before the fertilizer has lost more than 50% of its effective power after which is must be thrown away. The first four months of potency figures would look like this:Month 1, potency 100% Month 2, potency 94% Month 3, potency 88.36% Month 4, potency 83.0584% ... Loses potency at month xx
I don't necessarily want the answer, just a starting point.
CodePudding user response:
You could use a for loop or a while loop. Both works. Albeit I would probably use a while loop here as we aren't sure for how many iterations we need to go through.
The potency at month n
is given by 0.94^n
CodePudding user response:
Either works. For a class for "complete beginners", they'd almost certainly expect you to use a while
, because there's no fixed number of iterations to solve the problem, so a while
testing your stop condition is the straightforward solution; you'd just have to manually track how many months had passed along with computing the new efficacy rating each month.
With the simple tools available to beginners (no or minimal module imports), infinite for
loops aren't really a thing, but more advanced Python techniques would let you write an infinite for
loop that would track the month for you, e.g.:
for month in itertools.count(1): # Requires import itertools at top of file
# Perform your iterative recalculation of efficacy
# When it reaches 50%, break out of the loop and month will already have the correct value
but the distinction between the two solutions isn't enough to strongly favor one or the other (the for
would be microscopically faster, at the expense of requiring an import
, thanks to pushing some of the basic math to the C layer on the CPython reference interpreter).