[Tutor] printing puzzlement
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Fri, 9 Aug 2002 23:42:53 -0700 (PDT)
On Fri, 9 Aug 2002, Rob wrote:
> As seen in the C++ code snippet here, calculations are performed in the
> middle of the display of each line of output.
Yikes. It's usually not a good thing when "presentation logic" --- the
table display --- is so closely tied to the calculation logic. Perhaps we
can try to refactor this, and yank out the calculation into separate
functions.
> cout << "Pmt # Cur. Prin. Payment Int. Paid Rem. Prin." << endl;
> cout <<
> "----- ---------- ------- --------- ----------" << endl;
> for (int index = 0; index < numPayments; index++)
> {
> cout << setw(5) << right << (index + 1);
> cout << setw(12) << right << fixed
> << setprecision(2) << principle;
> cout << setw(9) << right << fixed << amtPayment;
> float interest =
> (float (int (principle * monthRate * 100) ) ) / 100.0;
> cout << setw(11) << right << fixed << interest;
> principle = principle + interest - amtPayment;
> cout << setw(12) << right << fixed << principle;
> cout << endl;
> }
Here's one possible way to recode this:
###
## Warning: untested code
class AmortizationSchedulePrinter:
def __init__(self, starting_principle, amtPayment, monthRate):
self.startingPrinciple = startingPrinciple
self.amtPayment = amtPayment
self.monthRate = monthRate
def printAmortizationSchedule(self):
self.printHeader()
p = self.startingPrinciple
for index in range(self.numPayments):
printReportLine(index, p)
p = self.nextPrinciple(p)
def printReportLine(self, index, principle):
print ("%5f"
"%12.2f"
"%9.2f"
"%11.2f"
"%12.2f") % \
(index + 1,
principle,
self.amtPayment,
self.interest(principle),
self.nextPrinciple(principle))
def nextPrinciple(self, principle):
return principle + self.interest(principle) - self.amtPayment;
def interest(self, principle):
return (float (int (principle * self.monthRate * 100) ) ) / 100.0;
def printHeader(self):
print "Pmt # Cur. Prin. Payment Int. Paid Rem. Prin."
print "----- ---------- ------- --------- ----------"
###
It is a bit longer than the original version, but it does allow us to make
changes to the line format more easily, since all of the formatting stuff
is in printHeader() and printReportLine().
Hope this helps!