我正在编写一个按年回报利息总额的测试。如何将我感兴趣的值附加到我的投资者类中数组interest = []
内的每一步上?出于某种原因,这很难绕过我的脑袋。
代码:
class Test(unittest.TestCase):
'''Represents my test case(s) for the dojo.'''
def setUp(self):
'''Defines the initial state of an investor.'''
self.investor = Investor(10000, 7.2, 5)
def test_solve_for_interest(self):
self.assertEqual(self.investor.get_interest(), 720.0)
def test_get_interest_by_year(self):
'''Returns a value of interest associated by the year.'''
self.assertEqual(self.investor.interest_by_year(1), 10720.0)
class Investor(object):
def __init__(self, amount, rate, time):
self.amount = amount
self.rate = rate
self.time = time
def get_interest(self):
return (self.amount * self.rate) / 100.0
def interest_by_year(self, year):
interest = []
for i in xrange(1, (self.time+1)):
# collect compounding interest each year
return interest[year]
预期结果:
year 1 = 10,720.00 (interest[1])
year 2 = 11491.84 (interest[2])
year 3 = 12319.25 (interest[3])
year 4 = 13206.24 (interest[4])
year 5 = 14157.09 (interest[5])
答案 0 :(得分:1)
Pandas可以更优雅地解决这个问题:
years = range(1,6)
rate = 0.072
rates = pandas.Series(index = years, data = rate)
请注意,这些年份的费率可能会有所不同
initialValue*((rates + 1).cumprod())
答案 1 :(得分:0)
def interest_by_year(self, year):
interest = [self.amount]
for i in xrange(self.time):
interest.append(interest[i]*self.rate)
return interest[year]
测试:
ivt = Investor(10000, 1.072, 10)
for i in range(1, 6):
print "year", i, "=", ivt.interest_by_year(i)
输出:
year 1 = 10720.0
year 2 = 11491.84
year 3 = 12319.25248
year 4 = 13206.2386586
year 5 = 14157.087842