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.
Related
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.
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, '%')
I'm attempting to take a starting balance and increase the value by 5% each month. I then want to feed this new balance back into the equation for the next month. I've attempted to do this using a while loop but it doesn't seem to be feeding the new balance back in.
I'm using 60 months (5 years) for the equation but this can be altered
counter = 1
balance = 1000
balance_interest = balance * .05
while counter <= 60:
new_monthly_balance = (balance + balance_interest)*(counter/counter)
print(new_monthly_balance)
balance = new_monthly_balance
counter += 1
You never change balance_interest in the loop.
What do you intend to do with *(counter/counter)? This merely multiplies by 1.0, which is a no-op.
while counter <= 60:
balance *= 1.05
print(balance)
counter += 1
Better yet, since you know how many times you want to iterate, use a for:
for month in range(60):
balance *= 1.05
print(balance)
BTW, just what sort of finance has a constant 5% monthly increase???
I am currently passing the sample tests and 2 of the other 10 cases so 4 out of 12. However, I don't make it through all of the data. I am getting a Terminated due to timeout error which means that my solution isn't fast enough.
def stockmax(prices):
total = 0
for index, price in enumerate(prices):
if index < len(prices) - 1:
section = max(prices[index+1:])
if prices[index] < section:
total += section - prices[index]
return total
I tried to do everything in only one loop. But how exactly can speed this type of question up. I also tried to cut some lines of the code but it is equally as inefficient.
def stockmax(prices):
total = 0
for index, price in enumerate(prices):
if index < len(prices) - 1 and prices[index] < max(prices[index+1:]):
total += max(prices[index+1:]) - prices[index]
return total
Though it passes the same amount of test cases.
I also tried to use heapq but it passes the same test cases and fails due to time.
def stockmax(prices):
total = 0
for index, price in enumerate(prices):
if index < len(prices) - 1:
section = heapq.nlargest(1,prices[index+1:])[0]
if prices[index] < section:
total += section - prices[index]
return total
https://www.hackerrank.com/challenges/stockmax/topics/dynamic-programming-basics
for details on the problem.
https://hr-testcases-us-east-1.s3.amazonaws.com/330/input09.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1538902058&Signature=3%2FnfZzPO8XKRNyGG0Yu9qJIptgk%3D&response-content-type=text%2Fplain
for a link of some test cases but will expire after a while.
Problem
Your algorithms have become so good at predicting the market that you now know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for the next number of days.
Each day, you can either buy one share of WOT, sell any number of shares of WOT that you own, or not make any transaction at all. What is the maximum profit you can obtain with an optimum trading strategy?
For example, if you know that prices for the next two days are prices = [1,2], you should buy one share day one, and sell it day two for a profit of 1. If they are instead prices = [2,1], no profit can be made so you don't buy or sell stock those days.
Function Description
Complete the stockmax function in the editor below. It must return an integer that represents the maximum profit achievable.
stockmax has the following parameter(s):
prices: an array of integers that represent predicted daily stock prices
Input Format
The first line contains the number of test cases t.
Each of the next t pairs of lines contain:
The first line contains an integer n, the number of predicted prices for WOT.
The next line contains n space-separated integers prices [i], each a predicted stock price for day i.
Constraints
1 <= t <= 10
1 <= n <= 50000
1 <= prices [i] <= 100000
Output Format
Output lines, each containing the maximum profit which can be obtained for the corresponding test case.
Sample Input
3
3
5 3 2
3
1 2 100
4
1 3 1 2
Sample Output
0
197
3
Explanation
For the first case, you cannot obtain any profit because the share price never rises.
For the second case, you can buy one share on the first two days and sell both of them on the third day.
For the third case, you can buy one share on day 1, sell one on day 2, buy one share on day 3, and sell one share on day 4.
Clearly, for any price we can buy, we would want to sell it at the highest price. Fortunately, we are given that highest price. So, iterating backwards, we know the highest future price seen at any point we visit in our travel "back in time."
Python code:
def stockmax(prices):
n = len(prices)
highest = prices[n - 1]
m = [0] * n
# Travel back in time,
# deciding whether to buy or not
for i in xrange(n - 2, -1, -1):
# The most profit buying stock at this point
# is what we may have made the next day
# (which is stored in m[i + 1])
# and what we could make if we bought today
m[i] = m[i + 1] + max(
# buy
highest - prices[i],
# don't buy
0
)
# Update the highest "future price"
highest = max(highest, prices[i])
return m[0]
If you can use Numpy, then something similar to the below should be rather quick (I believe it's the same idea as the answer from #גלעד ברקן).
import numpy as np
with open('.../input09.txt') as fd:
numtests = int(fd.readline().strip())
counter = 0
numvals = 0
vals = None
steps = None
for line in fd:
if (counter % 2 == 0) :
numvals = int(line.strip())
else:
vals = np.fromstring(line, dtype=int, sep=' ', count=numvals)
assert len(vals) == numvals
cum_max = np.maximum.accumulate(vals[::-1])
np.roll(cum_max, -1)
cum_max[len(cum_max) - 1] = 0
delta = (cum_max - vals)
print('#', counter + 1, 'sum:', np.sum(delta * (delta > 0)))
counter += 1
it runs almost instantly on tests from the input09.txt.
Here is my solution written in ruby.
The solution obtained perfect score.
def solution(a)
gain = 0
i = a.count - 1
min = false
mi = false
while i > 0
s = a.delete_at(i)
unless min
mi = a.index(a.min)
min = a[mi]
end
g = s - min
gain = g if g > gain
i -= 1
min = false if i == mi
end
gain
end
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.