Fun with Generators

Wednesday, January 14, 2009


Pointless post, just an example of a python generator (and list comprehension)

#! /bin/env python
from operator import add

originalPrincipal = 5300
ccAPR = 0.099

def ccBalance(principal, apr):
while(principal > 1.0):
minimum_payment = principal * 0.02
interest = ((principal * apr) / 12)
principal -= (minimum_payment - interest)
yield (principal, minimum_payment, interest)

leCardDeRipoff = ccBalance(originalPrincipal, ccAPR)
payments = [(x,y,z) for x,y,z in leCardDeRipoff]

print "paying the minimum balance on a credit card with"
print "a current balance of $"+ str(originalPrincipal) +" and"
print "an APR of " + str(100 * ccAPR) + "% will",
print "take " + str(len(payments) / 12.0) + " years"
print "and result in paying $",
print str(reduce(add, [z for x,y,z in payments])) + " in interest"



This is by no means a fast solution, take it with a grain of salt.... and wordpress flattens everything in code tags

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home