Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

a simpler way to sum up each value

# total payments = the sum of monthly payments
# object-level method for calculation in Loan class
    def totalPayments(self):
        # the monthly payment might be different depending on the period
        t = 0  # initialize the period
        m_sum = 0  # initialize the sum
        while t < self._term:  # run until we reach the total term
            m_sum += self.monthlyPayment(t)  # sum up each monthly payment
            t += 1  # go to next period
        return m_sum

monthly payment might be different depending on different period, so instead of simply multiplying it by term, I chose to sum up each payment individually. Is there a easier way of doing this?
I thought to do this at first

sum(payment for payment in self.monthlyPayment(t) if term <= t)

But t is not initialized and won’t be incremented to calculate each payment. So I was wondering if there is any easier approach that could possibly achieve the above functionality in a single line or so?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your variable t increments by 1 each time, so why don’t you use a range object?

for t in range(0, self._term+1):
    ...

So, if you want to mantain your comprehension, the best way should be this:

sum(self.monthlyPayment(t) for t in range(self._term))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading