I need the loop to follow the algorithm of the code below. Every loop should take the first day (2) and add the average (.3) to it.
startOrganism = 2
startOrganism = int(input("Starting number of organisms:"))
dailyInc = .3
dailyInc = float(input("Average daily increase (percent): "))
numberDaysMulti = 10
numberDaysMulti = int(input("Number of days to multiply: "))
for x in range(numberDaysMulti):
(Needs to be below)
Day 1 2
Day 2 2.6
Day 3 3.38
etc.
CodePudding user response:
Ok, I've assumed that the user will input the percent daily increase as 0.3
as opposed to 30
:
startOrganism = int(input("Starting number of organisms:"))
dailyInc = float(input("Average daily increase (percent): "))
numberDaysMulti = int(input("Number of days to multiply: "))
percDailyInc = 1 dailyInc
for day in range(numberDaysMulti):
print(f'Day {day 1} {startOrganism:.2f}')
startOrganism *= percDailyInc
Sample Output:
Day 1 2.00
Day 2 2.60
Day 3 3.38
Day 4 4.39
Day 5 5.71
Day 6 7.43
Day 7 9.65
Day 8 12.55
Day 9 16.31
Day 10 21.21
CodePudding user response:
This sort of computation can be handled mathematically, using the following formula:
organisms = starting_organisms * ((1.0 growth_rate) ^ days)
Where the growth_rate
is the percent increase per unit of time, in your case days. Then it becomes a matter of simply printing out the value for each day.
starting_organisms = int(input("Starting number of organisms:"))
growth_rate = float(input("Average daily increase in percent): ")) # 0.3 = 30%
period = int(input("Number of days to grow:"))
growth = [(starting_organisms * ((1.0 growth_rate) ** day) for day in range(period)]
# The list 'growth' has all our values, now we just print them out:
for day, population in enumerate(growth):
print(f"Day {day} {population}")
(This uses a zero-index for the days. That is, 'day 0' will be your starting number. Indexing this way saves you off-by-one errors, but you can change the print statement to be {day 1}
to hide this data structuring from the user.)
There is an alternative method where you carry state in each loop, calculating the next day as you iterate. However, I'd recommend separating the concern of calculation and display - that instinct will serve you well going forward.
The growth = [... for day in range(period)]
is a list comprehension, which works much like a one-line for-loop.