0% found this document useful (0 votes)
2 views

unit 3 python

This document provides an overview of plotting using PyLab, a Python library that mimics MATLAB functionalities for data visualization. It covers various types of plots including line plots, scatter plots, histograms, and mortgage-related plots, along with examples of code to generate these visualizations. Additionally, it discusses customizing plot appearances, adding informative titles, and using legends for clarity in multi-plot figures.

Uploaded by

Priyank Raychura
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit 3 python

This document provides an overview of plotting using PyLab, a Python library that mimics MATLAB functionalities for data visualization. It covers various types of plots including line plots, scatter plots, histograms, and mortgage-related plots, along with examples of code to generate these visualizations. Additionally, it discusses customizing plot appearances, adding informative titles, and using legends for clarity in multi-plot figures.

Uploaded by

Priyank Raychura
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIT 3: PLOTTING USING PYLAB

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 1

Plotting Using PyLab


PyLab is a Python standard library module that provides many of the facilities of MATLAB, “a
high- level technical computing language and interactive environment for algorithm
development, data visualization, data analysis, and numeric computation.”
Line Plot
A common type of graph to plot is a line relating x-values to particular y-values.

A simple example
Let’s start with a simple example that uses pylab.plot to produce two plots.
import pylab
pylab.plot([1,2,3,4], [1,2,3,4])
pylab.plot([1,4,2,3], [5,6,7,8])
pylab.show()
Executing the code will cause a window to appear on your computer monitor. Its exact
appearance will depend on the operating system on your machine, but it will always look
something like:

Sequences of the same length

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 2

The bar at the top contains the name of the window, in this case “Figure 1.” In this example, the
name is generated automatically by pylab.
The middle section of the window contains the plot generated by the two lines of code following
the import statement. The bottom line was generated by the statement pylab.plot([1,2,3,4],
[1,2,3,4]). Notice that the two arguments are lists of the same length. Together, they provide a
sequence of four <x, y> coordinate pairs, [(1,1), (2,2), (3,3),(4,4)]. These are plotted in order, and
then connected by a line. (Pylab automatically chooses the line color for each plot command, but
this can be overridden by an optional argument, as we shall see.) The zig zag plot at the top of
the middle section is produced the same way. It zig zags
because the sequence of Cartesian points being connected is [(1,5), (4,6), (2,7), (3,8)].

pylab.show()
The final line of code, pylab.show() causes the window to appear on the screen. If that line were
not there, the figure would still have been produced, but it would not have been displayed.

Introduction of the Buttons:


The bar at the bottom of the window contains a number of push buttons. The rightmost button is
used to write the plot to a file.3 The next button over is used to adjust the appearance of the plot
in the window. This is useful when there is more than one plot per figure. The next four buttons
are used for panning and zooming. And the button on the left is used to restore the figure to its
original appearance after you are done playing with pan and zoom.

The multiple figures


It is possible to produce more than one figure and to write them to files rather than the display.
The following code produces and saves to files named firstSaved.png and secondSaved.png the
two plots.

import pylab
pylab.figure(1)
pylab.plot([1,2,3,4], [1,2,3,4])
pylab.figure(2)
pylab.plot([1,4,2,3], [5,6,7,8])
pylab.savefig('firstSaved')
pylab.figure(1)
pylab.plot([5,6,7,10])
pylab.savefig('secondSaved')

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 3

firstSaved.png

secondSaved.png

One argument
Observe that the last call to pylab.plot is passed only one argument. This argument supplies the Y
values. The corresponding X values are range(len(Y-values)), which is why they range from 0 to
3 in this case.

“Current figure.”

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 4

Pylab has a notion of “current figure.” Executing the statement pylab.figure(x) sets the current
figure to the figure numbered x. Subsequently executed pylab commands implicitly refer to that
figure, until another pylab.figure command is executed. This explains why the plot on the left,
which corresponds to the figured numbered 2, is stored in firstSaved.png.

Compound interest Example:


import pylab
principal = 10000 #initial investment
interestRate = 0.05
years = 20
values = []
for i in range(years + 1):
values.append(principal)
principal += principal*interestRate
pylab.plot(values)
pylab.show()
The code produces the plot:

Informative Titles
If we look at the code, we can deduce that this is a plot showing the growth of an initial
investment of $10,000 with at an annually compounded interest rate of 5%. However, this cannot
be easily inferred looking only at the plot itself. That’s a bad thing. All plots should have
informative titles, and all axes should be labeled.
If we add to the end of our code(before show()) the following lines
pylab.title('5% Growth, Compounded Annually')
pylab.xlabel('Years of Compounding')
pylab.ylabel('Value of Principal ($)')

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 5

we get the more informative plot

Scatter plots
Alternatively, you may want to plot quantities which have an x and y position. For Example,
plotting the location of stars or galaxies in a field for example such as the plot.
Optional argument
For every plotted curve, there is an optional argument that is a format string indicating the color
and line type of the plot. The letters and symbols of the format string are derived from those used
in MATLAB, and are composed of a color indicator followed by an optional line-style indicator.
The default format string is 'b-', which produces a solid blue line. To plot the the growth in
principal with black circles, one would replace the call
pylab.plot(values, 'ko', )
which produces the plot:

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 6

The following format string characters are accepted to control the line style or marker:

character description

'-' solid line style

'--' dashed line style

'-.' dash-dot line style

':' dotted line style

'.' point marker

',' pixel marker

'o' circle marker

'v' triangle_down marker

'^' triangle_up marker

'<' triangle_left marker

'>' triangle_right marker

'1' tri_down marker

'2' tri_up marker

'3' tri_left marker

'4' tri_right marker

's' square marker

'p' pentagon marker

'*' star marker

'h' hexagon1 marker

'H' hexagon2 marker

'+' plus marker

'x' x marker

'D' diamond marker

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 7

character description

'd' thin_diamond marker

'|' vline marker

'_' hline marker

The following color abbreviations are supported:

character color

‘b’ blue

‘g’ green

‘r’ red

‘c’ cyan

‘m’ magenta

‘y’ yellow

‘k’ black

‘w’ white

Change the type size and line width


It is also possible to change the type size and line width used in plots. This can be done using
keyword arguments in individual calls to functions. E.g., the code:
principal = 10000 #initial
investment interestRate = 0.05
years = 20
values = []
for i in range(years + 1):
values.append(principal)
principal += principal*interestRate
pylab.plot(values, linewidth = 30)
pylab.title('5% Growth, Compounded Annually', fontsize = 'xx-large') pylab.xlabel('Years of
Compounding', fontsize = 'x- small')
pylab.ylabel('Value of Principal ($)')

produces the following plot:

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 8

Histograms
Histograms are very often used in science applications and it is highly likely that you will need to
plot them at some point! They are very useful to plot distributions
e.g. what is the distribution of galaxy velocities in my sample? etc. In Matplotlib you use the hist
command to make a histogram. Take a look at the short macro below which makes the plot.

import numpy as np
import pylab as pl
# make an array of random numbers with a gaussian distribution with
# mean = 5.0
# rms = 3.0
# number of points = 1000
data = np.random.normal(5.0, 3.0, 1000)
# make a histogram of the data array
pl.hist(data)
# make plot labels
pl.xlabel(’data’)
pl.show()
It will produce following output:

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 9

Mortgages
To install mortgage,
python -m pip install mortgage
simple example
from mortgage import Loan

loan = Loan(principal=200000, interest=.06, term=30)


loan.summarize
output:
Original Balance: $ 200,000
Interest Rate: 0.06 %
APY: 6.17 %
APR: 6.00 %
Term: 30 years
Monthly Payment: $ 1199.10

Total principal payments: $ 200,000.00


Total interest payments: $ 231,676.38
Total payments: $ 431,676.38
Interest to principal: 115.8 %
Years to pay: 30.0

Plotting Mortgages, an Extended Example


The methods plotPayments and plotBalance are simple one-liners, but they do use a form of
pylab.plot that we have not yet seen. When a figure contains multiple plots, it is useful to
produce a key that identifies what each plot is intended to represent. In Figure, each invocation of

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 10

pylab.plot uses the label keyword argument to associate a string with the plot produced by that
invocation. (This and other keyword arguments must follow any format strings.) A key can then
be added to the figure by calling the function pylab.legend, as shown in Figure. The nontrivial
methods in class Mortgage are plotTotPd and plotNet. The method plotTotPd simply plots the
cumulative total of the payments made. The method plotNet plots an approximation to the total
cost of the mortgage over time by plotting the cash expended minus the equity acquired by
paying off part of the loan.
import pylab
def findPayment(loan, r, m):
return loan*((r*(1+r)**m)/((1+r)**m - 1))
class Mortgage(object):
def __init__(self, loan, r, months):
self.loan = loan
self.rate = r/12.0
self.months = months
self.paid = [0.0]
self.owed = [loan]
self.payment = findPayment(loan, self.rate, months)
self.legend = None
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
def plotPayments(self, style):
pylab.plot(self.paid[1:], style, label = self.legend)
def plotBalance(self, style):
pylab.plot(self.owed, style, label = self.legend)
def plotTotPd(self, style):
"""Plot the cumulative total of the payments made"""
totPd = [self.paid[0]]
for i in range(1, len(self.paid)):
totPd.append(totPd[-1] + self.paid[i])
pylab.plot(totPd, style, label = self.legend)
def plotNet(self, style):
"""Plot an approximation to the total cost of the mortgage
over time by plotting the cash expended minus the equity
acquired by paying off part of the loan"""

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 11

totPd = [self.paid[0]]
for i in range(1, len(self.paid)):
totPd.append(totPd[-1] + self.paid[i])
#Equity acquired through payments is amount of original loan
# paid to date, which is amount of loan minus what is still owed
equityAcquired = pylab.array([self.loan]*len(self.owed))
equityAcquired = equityAcquired - pylab.array(self.owed)
net = pylab.array(totPd) - equityAcquired
pylab.plot(net, style, label = self.legend)
class Fixed(Mortgage):
def __init__(self, loan, r, months):
Mortgage.__init__(self, loan, r, months)
self.legend = 'Fixed, ' + str(r*100) + '%'
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 __init__(self, loan, r, months, teaserRate, teaserMonths):
Mortgage.__init__(self, loan, teaserRate, months)
self.teaserMonths = teaserMonths
self.teaserRate = teaserRate
self.nextRate = r/12.0
self.legend = str(teaserRate*100)\
+ '% for ' + str(self.teaserMonths)\
+ ' months, then ' + str(r*100) + '%'
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)

The next Figure contain functions that can be used to generate plots intended to provide insight
about the different kinds of mortgages. The function plotMortgages generates appropriate titles
and axis labels for each plot, and then uses the methods in MortgagePlots to produce the actual
plots. It uses calls to pylab.figure to ensure that the appropriate plots appear in a given figure. It
uses the index i to select elements from the lists morts and styles in a way that ensures that
different kinds of mortgages are represented in a consistent way across figures. For example,

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 12

since the third element in morts is a variable rate mortgage and the third element in styles is 'b:',
the variable-rate mortgage is always plotted using a blue dotted line.
The function compareMortgages generates a list of different mortgages, and simulates making a
series of payments on each, as it did in Chapter 8. It then calls plotMortgages to produce the
plots.
def plotMortgages(morts, amt):
styles = ['b-', 'r-.', 'g:']
payments = 0
cost = 1
balance = 2
netCost = 3
pylab.figure(payments)
pylab.title('Monthly Payments of Different $' + str(amt)+ ' Mortgages')
pylab.xlabel('Months')
pylab.ylabel('Monthly Payments')
pylab.figure(cost)
pylab.title('Cash Outlay of Different $' + str(amt) + ' Mortgages')
pylab.xlabel('Months')
pylab.ylabel('Total Payments')
pylab.figure(balance)
pylab.title('Balance Remaining of $' + str(amt) + ' Mortgages')
pylab.xlabel('Months')
pylab.ylabel('Remaining Loan Balance of $')
pylab.figure(netCost)
pylab.title('Net Cost of $' + str(amt) + ' Mortgages')
pylab.xlabel('Months')
pylab.ylabel('Payments - Equity $')
for i in range(len(morts)):
pylab.figure(payments)
morts[i].plotPayments(styles[i])
pylab.figure(cost)
morts[i].plotTotPd(styles[i])
pylab.figure(balance)
morts[i].plotBalance(styles[i])
pylab.figure(netCost)
morts[i].plotNet(styles[i])
pylab.figure(payments)
pylab.legend(loc = 'upper center')
pylab.figure(cost)
pylab.legend(loc = 'best')
pylab.figure(balance)
pylab.legend(loc = 'best')

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 13

pylab.show()

def compareMortgages(amt, years, fixedRate, pts, ptsRate,varRate1, varRate2, varMonths):


totMonths = years*12
fixed1 = Fixed(amt, fixedRate, totMonths)
fixed2 = FixedWithPts(amt, ptsRate, totMonths, pts)
twoRate = TwoRate(amt, varRate2, totMonths, varRate1, varMonths)
morts = [fixed1, fixed2, twoRate]
for m in range(totMonths):
for mort in morts:
mort.makePayment()
plotMortgages(morts, amt)

compareMortgages(amt=200000, years=30, fixedRate=0.07,pts = 3.25,


ptsRate=0.05,varRate1=0.045, varRate2=0.095, varMonths=48)
The call compareMortgages(amt=200000, years=30, fixedRate=0.07, pts = 3.25, ptsRate=0.05,
varRate1=0.045, varRate2=0.095, varMonths=48) produces plots that shed some light on the
mortgages.
The first plot, which was produced by invocations of plotPayments, simply plots each payment
of each mortgage against time. The box containing the key appears where it does because of the
value supplied to the keyword argument loc used in the call to pylab.legend. When loc is bound
to 'best' the location is chosen automatically. This plot makes it clear how the monthly payments
vary (or don’t) over time, but doesn’t shed much light on the relative costs of each kind of
mortgage. The next plot was produced by invocations of plotTotPd. It sheds some light on the
cost of each kind of mortgage by plotting the cumulative costs that have been incurred at the start
of each month. The entire plot is on the left, and an enlargement of the left part of the plot is on
the right.

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 14

The next two plots show the remaining debt and the total net cost of having the mortgage.

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 15

Fibonacci Sequences, Revisited


A straightforward recursive implementation of the Fibonacci function is shown here :
def fib(n):
"""Assumes n is an int >= 0 Returns Fibonacci of n"""
if n == 0 or n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
While this implementation of the recurrence is obviously correct, it is terribly inefficient. Try, for
example, running fib(120), but don’t wait for it to complete. The complexity of the
implementation is a bit hard to derive, but it is roughly O(fib(n)). That is, its growth is
proportional to the growth in the value of the result, and the growth rate of the Fibonacci
sequence is substantial. For example, fib(120) is 8,670,007,398,507,948,658,051,921. If each
recursive call took a nanosecond, fib(120) would take about 250,000 years to finish. Let’s try and
figure out why this implementation takes so long. Given the tiny amount of code in the body of
fib, it’s clear that the problem must be the number of times that fib calls itself. As an example,
look at the tree of calls associated with the invocation fib(6).

Notice that we are computing the same values over and over again. For example fib gets called
with 3 three times, and each of these calls provokes four additional calls of fib. 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, and
is the key idea behind dynamic programming.
Figure below contains an implementation of Fibonacci based on this idea. The function fastFib
has a parameter, memo, that it uses to keep track of the numbers it has already evaluated. The
parameter has a default value, the empty dictionary, so that clients of fastFib don’t have to worry
about supplying an initial value for memo. When fastFib is called with an n > 1, it attempts to
look up n in memo. If it is not there (because this is the first time fastFib has been called with
that value), an exception is raised. When this happens, fastFib uses the normal Fibonacci
recurrence, and then stores the result in memo.

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 16

def fastFib(n, memo = {}):


"""Assumes n is an int >= 0, memo used only by recursive calls Returns Fibonacci of n"""
if n == 0 or n == 1:
return 1
try:
return memo[n]
except KeyError:
result = fastFib(n-1, memo) + fastFib(n-2, memo)
memo[n] = result
return result
If you try running fastFib, you will see that it is indeed quite fast: fib(120) returns almost
instantly. What is the complexity of fastFib? It calls fib exactly once for each value from 0 to n.

Dynamic programming and the 0/1 Knapsack algorithm


Given weights and values of n items, put these items in a knapsack of capacity W to get the
maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and
wt[0..n-1] which represent values and weights associated with n items respectively. Also given
an integer W which represents knapsack capacity, find out the maximum value subset of val[]
such that sum of the weights of this subset is smaller than or equal to W. You cannot break an
item, either pick the complete item, or don’t pick it (0-1 property).

A simple solution is to consider all subsets of items and calculate the total weight and value of all
subsets. Consider the only subsets whose total weight is smaller than W. From all such subsets,
pick the maximum value subset.

1) Optimal Substructure:
To consider all subsets of items, there can be two cases for every item: (1) the item is included in
the optimal subset, (2) not included in the optimal set.
Therefore, the maximum value that can be obtained from n items is max of following two values.
1) Maximum value obtained by n-1 items and W weight (excluding nth item).

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 17

2) Value of nth item plus maximum value obtained by n-1 items and W minus weight of the nth
item (including nth item).
If weight of nth item is greater than W, then the nth item cannot be included and case 1 is the
only possibility.

2) Overlapping Subproblems
Following is recursive implementation that simply follows the recursive structure mentioned
above.
#A naive recursive implementation of 0-1 Knapsack Problem
# Returns the maximum value that can be put in a knapsack of capacity W
def knapSack(W , wt , val , n):
# Base Case
if n == 0 or W == 0 :
return 0
# If weight of the nth item is more than Knapsack of capacity
# W, then this item cannot be included in the optimal solution
if (wt[n-1] > W):
return knapSack(W , wt , val , n-1)

# return the maximum of two cases:


# (1) nth item included
# (2) not included
else:
return max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1),
knapSack(W , wt , val , n-1))

# end of function knapSack

# To test above function


val = [60, 100, 120]
wt = [10, 20, 30]
W = 50
n = len(val)
print knapSack(W , wt , val , n)
Output:
220
It should be noted that the above function computes the same subproblems again and again. See
the following recursion tree, K(1, 1) is being evaluated twice. Time complexity of this naive
recursive solution is exponential (2^n).

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 18

In the following recursion tree, K() refers to knapSack(). The two parameters indicated in the
following recursion tree are n and W. The recursion tree is for following sample inputs.
wt[] = {1, 1, 1}, W = 2, val[] = {10, 20, 30}

K(3, 2) ---------> K(n, W)


/ \
/ \
K(2,2) K(2,1)
/ \ / \
/ \ / \
K(1,2) K(1,1) K(1,1) K(1,0)
/ \ / \ / \
/ \ / \ / \
K(0,2) K(0,1) K(0,1) K(0,0) K(0,1) K(0,0)
Recursion tree for Knapsack capacity 2 units and 3 items of 1 unit weight.

Since suproblems are evaluated again, this problem has Overlapping Subprolems property. So
the 0-1 Knapsack problem has both properties of a dynamic programming problem. Like other
typical Dynamic Programming(DP) problems, recomputations of same subproblems can be
avoided by constructing a temporary array K[][] in bottom up manner. Following is Dynamic
Programming based implementation.

# A Dynamic Programming based Python Program for 0-1 Knapsack problem


# Returns the maximum value that can be put in a knapsack of capacity W
def knapSack(W, wt, val, n):
K = [[0 for x in range(W+1)] for x in range(n+1)]

# Build table K[][] in bottom up manner


for i in range(n+1):
for w in range(W+1):
if i==0 or w==0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])
else:
K[i][w] = K[i-1][w]

return K[n][W]

# Driver program to test above function


val = [60, 100, 120]
wt = [10, 20, 30]
W = 50

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 19

n = len(val)
print(knapSack(W, wt, val, n))
Output:
220

Divide and conquer


In divide and conquer approach, the problem in hand, is divided into smaller sub-problems and
then each problem is solved independently. When we keep on dividing the subproblems into
even smaller sub-problems, we may eventually reach a stage where no more division is possible.
Those "atomic" smallest possible sub-problem (fractions) are solved. The solution of all sub-
problems is finally merged in order to obtain the solution of an original problem.
Broadly, we can understand divide-and-conquer approach in a three-step process.

Divide/Break
This step involves breaking the problem into smaller sub-problems. Sub-problems should
represent a part of the original problem. This step generally takes a recursive approach to divide
the problem until no sub-problem is further divisible. At this stage, sub-problems become
atomic in nature but still represent some part of the actual problem.

Conquer/Solve
This step receives a lot of smaller sub-problems to be solved. Generally, at this level, the
problems are considered 'solved' on their own.

Merge/Combine
When the smaller sub-problems are solved, this stage recursively combines them until they
formulate a solution of the original problem. This algorithmic approach works recursively and
conquer & merge steps works so close that they appear as one.

Differentiate between Divide & Conquer Method vs


Dynamic Programming.
Divide & Conquer Method Dynamic Programming

1.It deals (involves) three steps at each level of 1.It involves the sequence of four steps:
recursion: o Characterize the structure of
Divide the problem into a number of optimal solutions.
subproblems. o Recursively defines the values of
Conquer the subproblems by solving them optimal solutions.
recursively.
o Compute the value of optimal
Combine the solution to the subproblems into
solutions in a Bottom-up

Compiled by: Kruti Kotak, Christ College, Rajkot


CS:33 Programming in Python 20

the solution for original subproblems. minimum.


o Construct an Optimal Solution
from computed information.

2. It is Recursive. 2. It is non Recursive.

3. It does more work on subproblems and 3. It solves subproblems only once and
hence has more time consumption. then stores in the table.

4. It is a top-down approach. 4. It is a Bottom-up approach.

5. In this subproblems are independent of each 5. In this subproblems are interdependent.


other.

6. For example: Merge Sort & Binary Search 6. For example: Matrix Multiplication.
etc.

Compiled by: Kruti Kotak, Christ College, Rajkot

You might also like