Python Prediction for organism population growth - python

The inputs would be:
The initial number of organisms
The rate of growth (a real number greater than 1)
The number of hours it takes to achieve this rate
A number of hours during which the population grows
I have:
Population = int(input("The initial number of organisms: " ))
RateOfGrowth = int(input("The rate of growth (a real number > 0): " ))
HrToAchieve = int(input("The number of hours it takes to achieve this rate: " ))
Input_Hrs = int(input("Enter the total hours of growth: " ))
NewGrowth = 0
Passes = Input_Hrs/HrToAchieve
while Passes > 0:
NewGrowth = (Population * RateOfGrowth)-Population
Population += NewGrowth
Passes -= 1
print("The total population is", Population )
New at loops and not sure how I'm missing a pass
partially working with input 10,2,2,6 providing correct answer of 80
But when using 100 organisms with growth rate of 5 over 2 hrs over 25 hrs total, I get 7000 NOT
24414062500 which would be proper.

You can do that in one line and Im assuming if the growth rate of x is there in y hours and there are less than y hours left, then there wont be any growth whatsoever.
import math
ORG = int(input("The initial number of organisms: " ))
GR = int(input("The rate of growth (a real number > 0): " ))
GR_Hr = int(input("The number of hours it takes to achieve this rate: " ))
PG_Hr = int(input("Enter the total hours of growth: " ))
Growth = ORG * int(math.pow(GR, PG_Hr//GR_Hr)) # or Growth = ORG * int(GR ** (PG_Hr // GR_Hr))
EDIT USING LOOPS
Growth_using_loops = ORG
loop_counter = PG_Hr//GR_Hr # double slash // returns a integer instead of float
for i in range(loop_counter):
Growth_using_loops = Growth_using_loops * GR
print(Growth)
print(Growth_using_loops)
Output :
The initial number of organisms: 100
The rate of growth (a real number > 0): 5
The number of hours it takes to achieve this rate: 2
Enter the total hours of growth: 25
24414062500
24414062500

Related

Right justify an f-string with multiple columns of data

Help me!! It's not justified (python)
# Accept the inputs
startBalance = float(input("Enter the investment amount: "))
years = int(input("Enter the number of years: "))
rate = int(input("Enter the rate as a %: "))
# Convert the rate to a decimal number
rate = rate / 100
# Initialize the accumulator for the interest
totalInterest = 0.0
# Display the header for the table V.3
print("%4s%18s%10s%16s" % \
("Year", "Starting balance",
"Interest", "Ending balance"))
# f string
# Compute and display the results for each year
for year in range(1, years + 1):
interest = startBalance * rate
endBalance = startBalance + interest
print(f"{year:>4}{startBalance:<18.2f}{interest:>10.2f}{endBalance:>16.2f}")
startBalance = endBalance
totalInterest += interest
# Display the totals for the period
print("Ending balance: $%0.2f" % endBalance)
print("Total interest earned: $%0.2f" % totalInterest)
I was trying to align data in a table on the right side of the column. I use f string and formatting type in the variable placeholder but there was no alignment.
I try to run the code on jupyter and VS Code.
There is no need to mix different template systems. Just use f-strings:
pv = float(input('Enter the investment amount: '))
years = range(int(input('Enter the number of years: ')))
rate = int(input('Enter the rate as a %: ')) / 100
interests = 0.0
print('Year Starting balance Interest Ending balance')
for year in years:
interest = pv * rate
fv = pv + interest
print(f'{year + 1:>4d}{pv:>17.2f}{interest:>10.2f}{fv:>16.2f}')
pv = fv
interests += interest
print(f'Ending balance: ${fv:0.2f}')
print(f'Total interest earned: ${interests:0.2f}')
And here is an example of the output:
Enter the investment amount: 200
Enter the number of years: 10
Enter the rate as a %: 15
Year Starting balance Interest Ending balance
1 200.00 30.00 230.00
2 230.00 34.50 264.50
3 264.50 39.67 304.18
4 304.18 45.63 349.80
5 349.80 52.47 402.27
6 402.27 60.34 462.61
7 462.61 69.39 532.00
8 532.00 79.80 611.80
9 611.80 91.77 703.58
10 703.58 105.54 809.11
Ending balance: $809.11
Total interest earned: $609.11

How to put like this maximum and minimum gross pay and number

How to make it right1
How to put like this maximum and minimum gross pay and number
you can create a list of gross_pays and you can get the maximum and minimum from the list
NUM_EMPLOYEES = int(input('Enter number of employees : '))
def main():
hours = []
number = 1
for index in range (NUM_EMPLOYEES):
employee = int(input(f"Enter the hours worked by employee {number}:"))
number += 1
hours.append(employee)
pay_rate= float (input("Enter the hourly pay rate : "))
number = 1
gross_pay2 = []
for index in hours:
gross_pay = index * pay_rate
print (f"Goss pay for employee {number}: ${gross_pay}")
gross_pay2.append(gross_pay)
number += 1
maximum=gross_pay2.index(max(gross_pay2))+1
minimum=gross_pay2.index(min(gross_pay2))+1
print(f'Employee {maximum} gets maximum gross pay: {max(gross_pay2)}')
print(f'Employee {minimum} gets minimum gross pay: {min(gross_pay2)}')
main()

Calculate a total from numbers produced by a for loop (running total)

My assignment is to calculate how much money a person would get if his salary started at 1 cent per day and doubled every day.
days = int(input("How many days will you work for pennies a day?"))
total_amount = ((2 ** (days - 1)) / 100)
print("Days Worked | Amount Earned That Day")
for num in range(days):
total_amount = format((2 ** (num) / 100), ',.2f')
print(num + 1, "|", "$", total_amount)
If I enter 15 for days, I can see the salary on each day, but I need the total amount earned over the 15 days.
I need the total amount earned over the 15 days
As a standard for loop example you want summation over each iteration. To achieve this, you initialize variable (total_accumulated in this case) with 0 and then add to this variable each intermediate result from each iteration, after loop is complete you print out final accumulated result like so (minimal editing of your original code):
days = int(input("How many days will you work for pennies a day?"))
total_amount = ((2 ** (days - 1)) / 100)
total_accumulated = 0
print("Days Worked | Amount Earned That Day")
for num in range(days):
current_pay = (2 ** (num) / 100)
total_accumulated += current_pay
total_amount = format(current_pay, ',.2f')
print(num + 1, "|", "$", total_amount)
print("Total accumulated:", str(total_accumulated))
As noted in comment to your question by #NiVeR this can be calculated directly, and this answer is aimed only at example with loops since this looks like classic case of exercise.
Keep track of today salary and previous day salary. previous to calculate today salary and today salary to calculate total
init_sal = .01
total = 0
today_sal = 0
days = int(input("How many days will you work for pennies a day?"))
for x in range(1, days+1):
if x == 1:
today_sal = init_sal
prev_sal = today_sal
else:
today_sal = prev_sal * 2
prev_sal = today_sal
total += today_sal
print ('$', today_sal)
print (total)

Python CD annual precentage

I am doing this assignment. when i input the number of months it is one printing one month. rather it be 5 months or 17 months its only printing 1 months total.
https://drive.google.com/file/d/0B_K2RFTege5uZ2M5cWFuaGVvMzA/view?usp=sharing
Here is what i have so far what am i over looking thank you
calc = input('Enter y or n to calculate your CDs worth?')
month= int(input('Select your number of months'))
while calc == 'y':
while month > 0:
amount = int(input('Please enter the amount:'))
percent= float(input('Please enter the annual percentage:'))
calc= amount + amount* percent/ 1200
print(calc)
You would want to use a for loop rather than while in this sense since you are doing a set amount of operations. You also were reusing calc and assigning calc to from a String to a float, generally a bad idea. The main problem is the formula builds upon the previously calculated number, it starts off with the initial amount entered, 10000 + 10000 * 5.75 / 1200 = 10047.91, then uses 10047.91 in the next calculation, instead of 10000, you never were reusing the previously calculated number, so you weren't getting the right answer. This should do it:
calc = input('Enter y or n to calculate your CDs worth?')
if calc == 'y':
month = int(input('Select your number of months'))
amount = int(input('Please enter the amount:'))
percent = float(input('Please enter the annual percentage:'))
for i in range(month):
if i == 0:
calcAmount = amount + ((amount * percent) / 1200)
else:
calcAmount = calcAmount + ((calcAmount * percent) / 1200)
print calcAmount

Multiple parameters definition of a function Python

I'm trying to write a function that calculates the cost of a loan, but I keep getting the cost of the loan to be the negative value of what the user inputs as the amount of the loan.
#define monthly payment
def MonthlyPayment (ammountOfLoan, numberOfPeriods,yearlyInterestRate):
ammountOfLoan = 0
numberOfPeriods = 0
yearlyInterestRate = 0
payment = [(yearlyInterestRate/12)/(1-(1+yearlyInterestRate/12))**(-numberOfPeriods)] * ammountOfLoan
return (payment)
#define cost of loan
def LoanCost(principal, month, payment):
period = 0
month = 0
payment = 0
cost = period * payment - principal
return (cost)
#calculate cost of loan
def main():
loan = float(raw_input("What is the ammount of your loan? "))
period = float(raw_input("How many months will you make payments? "))
rate = float(raw_input("What is the interest rate? "))
rate = rate / 100
MonthlyPayment(loan, period, rate)
costOfLoan = LoanCost(loan, period, rate)
print "The cost of the loan is $" + str(costOfLoan)
#run main
main()
LoanCost is setting period and payment to 0 (you're making the same mistake in MonthlyPayment, as well), then multiplying them. So you're ending up with (0 * 0) - principal. You're also calling the second parameter "month", when what you really mean is "period".
Just to clarify, when you have a function definition like
def func(a, b, c):
You shouldn't initialize a, b, and c to zero inside the function body. You're overwriting their values when you do that. Just use them directly.

Categories