Ploy
Ploy
Example
import pylab
#Create Figure 1
pylab.figure(1)
#Draw on Figure 1
pylab.plot([1,2,3,4],[1,2,3,4])
The above chart is the plot generated by the invocation of pylab.plot. The two parameters
of pylab.plot must be sequence of the same length. The first gives the x-coordinates of the
points to be plotted and the second the y-coordinates. Combination of these two(x,y)
provides of FOUR <x , y> coordinated pairs [(1,1), (2,2), (3,3), (4,4)].
#Plotting to Canvas
plt.plot([1,2,3,4],[4,5,1,3])
Above code will generate two plots. First plot will be saved as “myFig_01.png” and
Second plot will be saved as “myFig_02.pdf”. Supported formats are : eps, pdf, pgf, png, ps,
raw, rgba, svg, svgz.
Out Put
For a 30 year mortgage loan of Rs.100,000
at an annual interest rate of 7.50%
you pay Rs.699.21 monthly
==================================================
Total amount paid will be Rs.251,717.22
class Mortgage(object):
"""Abstract class for building different kinds of mortgages"""
def makePayment(self):
"""Make a payment"""
self.paid.append(self.payment)
reduction = self.payment - self.owed[-1]*self.rate
self.owed.append(self.owed[-1] - reduction)
def getTotalPaid(self):
"""Return the total amount paid so far"""
return sum(self.paid)
def __str__(self):
return self.legend
Looking at __init__, we see that all Mortgage instances will have instance variables
corresponding to the initial loan amount, the monthly interest rate, the duration of the loan in
months, a list of payments that have been made at the start of each month (the list starts with 0.0,
since no payments have been made at the start of the first month), a list with the balance of the
loan that is outstanding at the start of each month, the amount of money to be paid each month
(initialized using the value returned by the function findPayment), and a description of the mortgage
(which initially has a value of None). The __init__ operation of each subclass of Mortgage is
expected to start by calling Mortgage.__init__, and then to initialize self.legend to an
appropriate description of that subclass.
The method “makePayment()” is used to record mortgage payments. Part of each payment
covers the amount of interest due on the outstanding loan balance, and the remainder of the
payment is used to reduce the loan balance. That is why “makePayment()” updates both
self.paid and self.owed.
The method “getTotalPaid()” uses the built-in Python function sum, which returns the sum of
a sequence of numbers. If the sequence contains a non-number, an exception is raised.
class FixedWithPts(Mortgage):
def __init__(self, loan, r, months, pts):
Mortgage.__init__(self, loan, r, months)
self.pts = pts
self.paid = [loan*(pts/100.0)]
self.legend = “Fixed, “ + str(r*100) + “%, “\ + str(pts) + “ points”
class TwoRate(Mortgage):
def makePayment(self):
if len(self.paid) == self.teaserMonths + 1:
self.rate = self.nextRate
self.payment = findPayment(self.owed[-1], self.rate,
self.months - self.teaserMonths)
Mortgage.makePayment(self)
Above Code contains a third subclass of Mortgage. The class TwoRate treats the
mortgage as the concatenation of two loans, each at a different interest rate. (Since
self.paid is initialized with a 0.0, it contains one more element than the number of
payments that have been made. That’s why makePayment compares
len(self.paid) to self.teaserMonths + 1).
for m in range(totMonths):
for mort in morts:
mort.makePayment()
for m in morts:
print m
print “Total payments = Rs.” + str(int(m.getTotalPaid()))
Above Code contains a function that computes and prints the total cost of each kind of
mortgage for a sample set of parameters. It begins by creating one mortgage of each
kind. It then makes a monthly payment on each for a given number of years. Finally, it
prints the total amount of the payments made for each loan.
Out Put
Fixed, 7.0%
Total payments = Rs. 479017
In Python, we can also add PLOTs to above examples to illustrate Graphical Mortgages.
Example
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms: "))
print("Fibonacci sequence:")
for i in range(n):
print (fibonacci(i))
Out Put
Enter number of terms: 5
Fibonacci sequence:
0
1
1
2
3
Notice that we are computing the same values over and over again. For example
Fibonacci() gets called with 5 Five times, and each of these calls provokes Six additional
calls of Fibonacci(). It doesn’t require a genius to think that it might be a good idea to
record the value returned by the first call, and then look it up rather than compute it each
time it is needed. This is called “Memoization (to be remembered)", and is the key idea
behind dynamic programming.
class Item(object):
def __init__(self, n, v, w):
self.name = n
self.value = float(v)
self.weight = float(w)
def getName(self):
return self.name
def getValue(self):
return self.value
def getWeight(self):
return self.weight
def __str__(self):
result = '<' + self.name + ', ' + str(self.value)\
+ ', ' + str(self.weight) + '>'
return result
def value(item):
return item.getValue()
def weightInverse(item):
return 1.0/item.getWeight()
def density(item):
return item.getValue()/item.getWeight()
def buildItems():
names = ['clock', 'painting', 'radio', 'vase', 'book', 'computer']
values = [175,90,20,50,10,200]
weights = [10,9,4,2,1,20]
Items = []
for i in range(len(values)):
Items.append(Item(names[i], values[i], weights[i]))
return Items
def greedy(items, maxWeight, keyFunction):
"""Assumes Items a list, maxWeight >= 0,
keyFunction maps elements of Items to floats"""
itemsCopy = sorted(items, key=keyFunction, reverse = True)
result = []
totalValue = 0.0
totalWeight = 0.0
for i in range(len(itemsCopy)):
if (totalWeight + itemsCopy[i].getWeight()) <= maxWeight:
result.append(itemsCopy[i])
totalWeight += itemsCopy[i].getWeight()
totalValue += itemsCopy[i].getValue()
return (result, totalValue)
def testGreedy(items, constraint, keyFunction):
taken, val = greedy(items, constraint, keyFunction)
print (“Total value of items taken = “, val)
for item in taken:
print (“ “, item)
def testGreedys(maxWeight = 20):
items = buildItems()
print (“Use greedy by value to fill knapsack of size”, maxWeight)
testGreedy(items, maxWeight, value)
print (“\nUse greedy by weight to fill knapsack of size”, maxWeight)
testGreedy(items, maxWeight, weightInverse)
print (“\nUse greedy by density to fill knapsack of size”, maxWeight)