Sum the value of range column - python

tuition = 10966
increase_rate = 0.062
# print headings
print("Year #\t\tProjected Annual Tuition")
print("----------------------------------------")
for y in range(1, 5):
tuition_inc = tuition*increase_rate
tuition += tuition_inc
print(y, "\t\t$", format(tuition, ",.2f"), sep='')
How to sum the column of Projected Annual Tuition? When use the sum function it is summing the years and not the amount of all 4 years tuition combined.

Try first defining the total first outside of the loop -
total = 0
And then inside the loop use
total += tuition
so you can actually save the total, and then have it equal the sum of all the tuition years.

Related

How to get a final report in years in for statement

for p in range(running_weeks):
#Increase weeks in output
output_weeks = output_weeks + 1
#For backend to reset the total
function_total = function_total + income
#Real total shown in output
true_total = true_total + income
print("Week", output_weeks, "Income", income, "Total", true_total)
#For every 3000 in total the income increases and the functional total goes to 0
if math.floor(function_total / money_needed_for_increase) == 1:
income = income + increase_income
function_total = 0;
print("\nIncome increased by: ", increase_income, "\n")
#Every 52 weeks this message pops
if output_weeks % 52 == 0:
print("\nYear ", output_weeks / 52, "Done Results: Income:", income, "Total", true_total,"\n")
With this for statement I'm able to see what happens each week and how much my income will increase and when the year is over. But, I would like to add something so that when the for statement is over, it shows a result of how much I made each year.
Ex:
Year 1.0 Income: 10,000 Total: 100,000
Year 2.0 Income: 11,000 Total: 500,000
and so on
If I understand correctly, you want to split running_weeks into full years. You can simple use a for loop for that. Here's the example:
years = []
for i in range(0, len(running_weeks), 52):
years.append(running_weeks[i : i + 52])
It will split running_weeks into few pieces of size 52. Then you can easily calculate all data about each year.
Try tracking years as a list of sublists, then iterate through the years at the end. So before your code, add the years list:
years = []
for p in range(running_weeks):
And as you total each year, append to years:
#Every 52 weeks this message pops
if output_weeks % 52 == 0:
print("\nYear ", output_weeks / 52, "Done Results: Income:", income, "Total", true_total,"\n")
years.append[[income, true_total]]
Then at the end, iterate through the years. Indexes start at 0 and you want year 0 to be treated as 1, so use i+1:
for i in range(len(years)):
year_income, year_total = years[i]
print('Year', i+1, 'Income:', year_income, 'Total:', year_total)

Python function for calculating compound interest percentage

I'm new to programming, so any experienced programmer will probably be able to answer this question easily.
I am trying to write a Python function which will tell me what percentage compound interest is necessary to end up with a specific sum. For example, if I deposited $100, and after 17 years of compound interest I have $155, the function will tell me what percentage interest was I receiving. I wrote the following function, with 'start' being the original sum deposited, 'finish' the sum I ended up with, and 'years' the number of years it accrued interest. I designed it to give a result in decimal points, for example for 1.5% it will show 0.015.
Here's the code I wrote:
def calculate(start, finish, years):
num = start
percentage = 0
while num < finish:
percentage += 0.000001
for year in range(years):
num += num * percentage
return percentage
print(calculate(12000, 55000, 100))
It's giving an output of 0.00017499999999999962 (i.e. 0.017499999999999962%), which is totally wrong.
I can't understand where I've gone wrong.
You need to reset the num=start after every time you guess a percentage.
def calculate(start, finish, years):
num = start
percentage = 0
while num < finish:
num = start
percentage += 0.000001
for year in range(years):
num += num * percentage
return percentage
print(calculate(12000, 55000, 100))
However, you'd probably be better off solving this problem by simply re-arranging the compound interest formula:
A=P*(1+r/n)^(nt)
(where A = Final balance, P = Initial balance, r = Interest rate, n = number of times interest applied per time period, and t = number of time periods elapsed.)
The rearrangement gives:
r=n((A/P)^(1/nt)-1)
and putting this into python gives us:
def calculate(start, finish, years):
num = ((finish / start)**(1/years))-1
return num
print(calculate(12000.0, 55000.0, 100.0))
which gives the expected results.
You can do a one-liner if you understand how compound interest works
def calculate(start, finish, years):
return (finish/start)**(1/years) - 1
print(calculate(12000, 55000, 100) * 100, '%')

Trying to print correct element corresponding to value

def main():
rain = [] # empty list awaiting user input
MONTH = ["January", "February"] # parallel to the rain?
SIZE = 2 # array size
getRain(rain,SIZE) # ask user to input each month rainfall amount
highest = findHigh(rain, SIZE, MONTH)
displayValues(SIZE, highest, rain)
# get input and add to list
def getRain(rain, SIZE):
index = 0
while (index <= SIZE - 1):
print('Enter rainfall for month', index + 1)
rainInput = int(input('Enter rainfall: '))
rain.append(rainInput)
index = index + 1
# finding the highest value in the array and printing the highest value with month
def findHigh(rain, SIZE, MONTH):
highest = rain[0]
index = 1
while (index <= SIZE - 1):
if (rain[index] > highest):
highest = rain[index]
else:
index = index + 1
print("The highest month is:", MONTH[index - 1]) # not too sure if I need this here
return highest
# display the values
def displayValues(SIZE, highest, rain):
print("--------------------------------")
print("The highest value is:", highest)
# run code
main()
Hi, I am trying to figure out how to get it so then my output would print the right month in correlation to the amount of rainfall each month has (for example: january has 50 and february has 40)
Output: The highest month is: January
I've tried making another condition thing or another module to try to check the values, but I cannot compare strings to int in the list. I have also tried moving the print values but I feel like another module would be needed to find the right month unless I am just printing it in the wrong area
If you don't want to change the rest of the code, you can modify findHigh to track and print the month with the highest value:
def findHigh(rain, SIZE, MONTH):
highest = 0
index = 1
while (index <= SIZE - 1):
if (rain[index] > rain[highest]):
highest = index
else:
index = index + 1
print("The highest month is:", MONTH[highest]) # not too sure if I need this here
return rain[highest]
or slightly more pythonic:
def findHigh(rain, SIZE, MONTH):
highest = 0
for index in range(SIZE):
if rain[index] > rain[highest]:
highest = index
print("The highest month is:", MONTH[highest]) # not too sure if I need this here
return rain[highest]
It may be better to move both the prints to displayValues:
def main():
rain = [] # empty list awaiting user input
MONTH = ["January", "February"] # parallel to the rain?
SIZE = 2 # array size
getRain(rain,SIZE) # ask user to input each month rainfall amount
highest = findHigh(rain, SIZE)
displayValues(SIZE, highest, rain, MONTH)
# get input and add to list
def getRain(rain, SIZE):
index = 0
while (index <= SIZE - 1):
print('Enter rainfall for month', index + 1)
rainInput = int(input('Enter rainfall: '))
rain.append(rainInput)
index = index + 1
# finding the highest value in the array and printing the highest value with month
def findHigh(rain, SIZE):
highest = 0
for index in range(SIZE):
if rain[index] > rain[highest]:
highest = index
return highest
# display the values
def displayValues(SIZE, highest, rain, MONTH):
print("The highest month is:", MONTH[highest]) # not too sure if I need this here
print("--------------------------------")
print("The highest value is:", rain[highest])

Python Investment Calculator

Please I need help to figure out this. I don't know where I go off.
The Assignment is :
"Write a function investment(PMT, n, i) that calculates your customer's savings at some point in the future, if:
an amount is invested at the END of every year, starting with amount
of PMT at the end of this year,
at an interest rate of i% per year, compounded annually,
the investment amount doubles every second year (cumulatively)."
And there is my code:
def investment(PMT, n, i):
x = 0
while x < n:
if x % 2 == 1:
PMT = 2*(PMT*(1 + i)**n)
else:
PMT = PMT*(1 + i)**n
x = x + 1
investment_balance = PMT
return round(investment_balance, 2)
The answer supposed to be: investment(15000, 30, 0.1045) == 1954935238.47 but I am getting: 3.4728768295747016e+47.
The formula you're using looks like the one you'd use to calculate the future value of money with compound interest. That's on the right track, but you don't want to do that computation in a loop. Your results will be too large.
Try this instead.
Set the initial investment balance to 0.
Start looping over x number of years.
If the year is odd (because we start counting at 0), double the payment.
Apply the interest to the balance.
Add the payment to the balance.
It's important to do that last step last because we're only adding the payment at the end of each year. That means interest shouldn't be applied in year 0. (More accurately, it will be applied to a 0 balance.)
If you do all that, you get a function that looks like this:
def investment(PMT, n, i):
x = 0
investment_balance = 0
while x < n:
if x % 2 == 1:
PMT = 2* PMT
investment_balance *= (1 + i)
investment_balance += PMT
x = x + 1
return round(investment_balance, 2)
This works for the example input you gave.
A couple observations:
Since the payment is made at the end of the year and interest is i% per year there should be no interest at the end of the first year.
If the investment doubles every second year you could calculate the effective interest rate over 2 years and then compound bi-annually (every second year). As in run this as a normal compound interest equation where PMT is doubled each compounding. Should make the logic a little easier. For odd n's you'd have to do a last compounding using the original rate.
Your equation is overwriting PMT on each loop. The PMT doesn't increase with interest, only doubled every second year. If PMT was $100 in year 0, it should only be $200 in year 2 instead of being compounded three times by your loop.

algorithm that calculates a minimum amount to be paid to pay off a balance in 12 months

I'm struggling with a problem that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, I mean a single number which does not change each month, but instead is a constant amount, multiple of 10 and the same for all months, that will be paid each month. ( it is possible for the balance to become negative using this payment scheme, which is OK)
So as input I have
original_balance = 3329
annualInterestRate = 0.2
From this I'm calculating the followings :
after_12_months_interest = original_balance
monthlyInterestRate = round(annualInterestRate/12.0,2)
monthly_payment = 10
total_paid = 0
for i in range(0,12):
after_12_months_interest = after_12_months_interest + (annualInterestRate/12.0)*after_12_months_interest
while total_paid < after_12_months_interest:
new_balance = 0
unpaid_balance = original_balance - monthly_payment
total_paid = 0
for i in range(0, 13):
total_paid = total_paid + monthly_payment
if total_paid < after_12_months_interest:
monthly_payment = monthly_payment + 10
print "Lowest Payment: ", monthly_payment
My problem I have is that I end up having a monthly_payment just a little more than I should have it. In this case the return for the monthly_payment is 320 instead of 310. For all use cases I've tried the monthly_payment it's slightly more than it should be.
Anyone can give me a hint or an idea on what I'm doing wrong please. Thank you
Mandatory one-liner
from itertools import count
print(next(payment for payment in count(0, 10)
if sum(payment*(1+monthly)**i for i in range(12)) > original_balance*(1+annual)))
What this does:
next takes the first element of an iterator.
count tries values from 0 to infinity (only each time next is called, and only until a value is returned)
sum(payment*(1+monthly)**i for i in range(12)) That's the combined value of the payments. Each payment is worth itself plus all the saved interests (the earlier you repay, the less interest you'll owe later)
original_balance*(1+annual) is indeed the total value if nothing is repayed.
Alternative
print(next(payment for payment in count(0, 10)
if reduce(lambda x,_:(x - payment)*(1+monthly), range(12), original_balance) <= 0))
This one computes the combined remainder of the debt by reduceing the original_balance 12 times.

Categories

Resources