Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Python Programming Languages

Uploaded by

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

Python Programming Languages

Uploaded by

Vishal Dagade
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

[] Notes 1 ..

gf 69+

SECOND YEAR B. Sc. -

COMPUTER SCIENCE SEMESTER-IV

PYTHON
PROG1
RAMMING IANGUAGE-11
Mathematics Practical (MTC-Z43J : Paper-HI

HRISHIKfSH KHAIAOKAR N. '9. PHATMl&\RE


Dr. A. S. KHAIRNAR Dr. S. G. PU~'JE

CBCS
2 c.REDIIS
[I] Notes ,t ~ 6 ~f 69+ >>

S\iflabus ...
1. 2D, 3D Graphs
1.1 Installation of numpy, matplotlib packages.
1.2 Graphs plotting of functions such as ... etc.
1.3 Different formats of graphs.
1.3 Three-dimensional Points and Lines.
1.4 Three-dimensional Contour Plots.
1.5 Wireframes and Surface Plots.
1.6 Graphs plotting of functions such as ... etc.
2. Computational Geometry
2.1 Points: The distance between two points, Lists of Points - the Point List class,
Integer points lists, Ordered Point sets, Extreme Points of a Point List, Random sets
of Points not in general position.
2.2 Points: Displaying points and other geometrical objects, lines, rays, and line
segments, The geometry of line segments, Displaying lines, rays and line segments.
2.3 Polygon: Representing polygon in Python, Triangles, Signed area of a triangle,
Triangles and the relationships of points to lines is, collinear, is Left, is Left On, is
Right, is Right On, Between.
2.4 Two dimensional rotation and reflection.
2.5 Three dimensional rotation and reflection.
2.6 Generation of Bezier curve with given control points.
3. Study of Operatlonal Research In Python
3.1 Linear Programming in Python.
3.2 Introduction to Simplex Method in Python.
Notes , ...Q I) >>

Commts
1. 2D, 3D Graphs 1.
1.1 Installation of Numpy and Matplotlib Packages 1
1.1.1 Installation of Numpy and Matplotlib 1
1.2 Graph plotting using Matplotlib 2
1.2.1 Logarithmic functions 2
1.2.2 Trignometric Functions 3
1.2.3 Inverse Trignometric Functions 3
1.2.4 Algebraic Functions 4
1.2.S Exponential Functions 5
1.2.6 General combination of LIATE function 5
1.2.7 Visualising a Three Dimensional Function in Two dimensions 6
1.3 Different formats for Graphs in Python 7
1.3.1 Line Graphs 7
1.3.2 Bar graphs 8
1.3.3 Histogram 9
1.3.4 Pie chart 10
1.3.S Scatter plots 11
1.4 Three dimensional Points and Lines 11
1.5 Three dimensional contour plots 14
1.6 Wireframes and Surface plots 15
1.7 Surface Triangulations 16
1.8 Self Exercises 17
2. Computational Geometry 21
2.1 Points 21
2.1.1 Point class 21
2.1.2 Euclidean distance between points 23
2.1.3 List of points: Point List class 23
2.1.4 Integer Point Lists 26
2.1.5 Ordered Point Sets 26
2.1.6 Extreme Points 27
2.1.7 Random Set of Points not in any General Position 27
2.2 Displaying Points and Other Geometrical Objects 28
2.2.1 Line, Rays and Line Segments 32
2.2.2 Displaying Lines, Rays and Line Segments 34
2.3 Polygons 36
2.3.1 Triangle 37
2.3.2 Signed Area of a triangle 38
2.3.3 Triangles and the relationships of points to the lines 39
2.4 Two dimensional rotation and reflection 40
2.5 Three dimensional rotation and reflection 42
2.6 Bezier Curve with Control Points 44
2.7 Self Exercises 47
3. Study of Operations Research In Python 49
3.1 Linear Programming in Python 49
3.1.1 Basic Terminologies 49
3.2 Introduction to Simplex Method in Python 52
3.3 Self Exercises 54
Chapter 1

2D, 3D Graphs

1.1 Installation of Numpy and Matplotlib Packages


Numpy is a Python Library which supports large multidimensional arrays and matrices along
with a large collection of high level mathematical functions to operate on these arrays.
Matplotlib is a plotting library in Python which is an extension of numpy. It provides object
oriented API for embedding plots in to applications using general purpose GUI tools like Tkinter,
wxpython, Qt and GTK+.

1.1.1 Installation of Numpy and Matplotlib


Note that before installing any external packages in Python, PIP is installed in Python. PIP
which stands for Python lnstaJI Packages works as a Package instaJJer for Python. ln order to
install Numpy and Matplotlib on Mac Operating system open the terminal and type the following
commands:
XYZ-Macbook-Pro:~pip3 install numpy
XYZ-Macbook-Pro:~pip3 install matplotlib
On the windows operating system again go to the terminal and type;
C:\Users\XYZ>pip3 install numpy
C:\Users\XYZ>pip3 install matplotlib
On the linux operating system again go to the terminal and type;
root@user:~ sudo pip3 install numpy
root@user:~ sudo pip3 install matplotlib
S.Y.B.Sc.(Computer Science) Python Programming Language IT

1.2 Graph plotting using Matplotlib


As mentioned earlier Matplotlib is a Graphing library which is used to plot various graphs. In this
section we will sec how to use Matplotlib to plot Mathematical Functions. Note that the library
Numpy will be used to evaluate these mathematical functions on a set of values on which these
functions will be defined.

1.2.1 Logarithmic functions


To plot the function f(x ) = log 10(x) on the interval [O, 10). Refer the code below;

import matplotlib.pyplot as plt


import numpy as np
x = np.linspace(8,18)
y ;;; np.log18(x)
plt.plot(x, y)
plt.show()

Note that,

• np. linspace () : initializes the interval on which this function is defined.

• np. log18() : computes the value of the logarithm to the base 10.

• pl t. plot() : plots the points on the canvas.

• pl t. show() : display the plot.

0 6 8 10

Fig. 1.1 : Plot of /(x) = log 10 (x)

2 CHAPTER I. 20. JD GRAPHS


S.Y.B.Sc.(Computer Science) Python Programming Language Il

1.2.2 Trignometric Functions


To plot the function f(x) = cos(x) on the interval [O, 2,r] refer the code below;

mport matplotlib.pyplot as plt


import numpy as np
x = np . arange(&, 2*(np.pi), 8.1)
y = np.cos(x)
plt . plot(x, y)
plt . show()
Note that

• np.arangeQ: is used to plot points in the specified interval with a specified distance

• np.cosO: calculates the cosine of the values on which the interval where it is defined

l OO

07S

oso
0 25

000

--0.25
--0.50

--0 75

- 1.00
0 2 3 4 5 6

Fig. 1.2 : Plot of the function f(x) = cosx

1.2.3 Inverse Trignometric Functions


To plot the function f (x) = sin- 1(x) on the interval [ -1, l] refer the code below;
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-1, 1, 8.81)
y = np . arcsin(x)
plt.plot(x, y)
plt.show()

3
CHAPTER I. 2D, 3D GRAPHS
S.Y.B.Sc.(Computer Science) Python Programming Language n

Note that,

• np . arcsin() will calculate the values of the inverse sine function for a given set of values.

15

10

0.5

00

-0 5

-1.0

-1.5

-1 00 -0 75 -050 -0.25 0.00 D.25 0.50 0_75 100

1
Fig. 1.3: Plot of the function /(x} = sin- (x)

••
"
30

2.5

,..
IS

LO

.,
00
_, 0 - 1' -l 0 ..,,
Fig. 1.4 : Plot of the function/ (x) = x2

1.2.4 Algebraic Functions


To plot the function /(x) = x 2 on the interval [-2, 2) refer the code below;

mport matpl otlib.pypl ot as plt


import numpy as np
x = np. l inspace(-2 , 2, 188)
y = X ** 2
fig= plt.figure(figsize = (18 , 5))

4 CHAPTER I. 20, 3D GRAPHS


S. Y.B.Sc.(Computer Science) Python Programming Language [I

plt.plot(x, y)
plt.show()
Note that

• pl t. figure() creates a plot of the given size. For plot of f {x) = x2 see the Fig. l.4.

1.2.S Exponential Functions


To plot the function f(x ) = tr on the interval [-1 , JOO] refer the code below:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 2, l&&)
y = np.exp(x)
plt.plot(x,y)
plt.sbow()
Note that

• np.exp() computes the exponential of the values given.

- 10 -OS 00 OS 10 15 2.0

Fig. 1.5 : Plot of the function f (x ) = tr

1.2.6 General combination of LIATE function


To plot the functions f{x) = sinx - tr + 3x2 - Iog10 x on the interval [O, 2,r]

5 CHAPTER I . 20. 3D GRAPHS


S.Y.B.Sc.(Computer Science) Python Programming Language II

import matplotlib.pyplot as plt


import numpy as np
x = np.arange(& , 2*(np.pi), &.l)
y=np.sin(x)-np.exp(x)+3*x**2+np.logl&(x)
pl t. plot (x, y)
plt.show()

· 100
· UO
.,oo

-lSO
-lOO

- )SO

Fig. 1.6 : Plot of the combination LIATE, f (x) = sin x - ex + 3x2 - log 10 x

1.2.7 Visualising a Three Dimensional Function in 1\vo dimesnions


Sometimes it is useful to represent a three dimensional function in two dimension using contours
or color coded reigons.
Let us first define a function f(x, y) = sin 10 (x) + cos(5 + xy) sin (x).
To plot the contour corresponding to the above function refer the code below;

import numpy as np
import matplotlib.pyplot as plt
plt.style.use( ' seaborn-white')
def f(x, y):
retwn np.sin(x) ** l& + np .cos(5 + y * x) * np.sin(x)
x = np.linspace(&, 5, 5&)
y = np.linspace(&, 5, 5&)
X, Y = np.meshgrid(x, y)
Z = f(X,Y)
plt.contourf(X, Y, Z, 2&, cmap='RdBu')
pl t. colorbar ()
Note that,

6 CHAPTER I. 20. 3D GRAPHS


S.Y.B.Sc.(Computer Science) Python Programming Language IT

• np. meshgrid() is used to construct a grid corresponding to the two given arrays.
• pl t. contour£() is used to construct the contour corresponding to a given function.

• pl t. colorbar () is used to represent the density represented in terms of colours.


21
II
IS
11
09
06
OJ

00
-<) )

_.,,

Fig. 1.7 : Contour Plots

1.3 Different formats for Graphs in Python


1.3.1 Line Graphs
A Line Graph is a chart which is used to show some information that changes over time. The
Graph is plotted by connecting various points by straight line segments. These kind of graphs are
usually used to represent a time series data.
Refer the code below;
import matplotlib.pyplot as plt
xl = [1,2,3]
yl = [3,6,2]
plt.plot(xl, yl, label = "line 1")
x2 = [1,2, 3]
y2 = [7, 2, SJ
plt.plot(x2, y2, label = "line 2")
plt.xlabel('x - axis')
plt .ylabel (' y - axis')
plt.title('Two lines on same graph!')
pl t . legend()
plt.show()

CHAPTER I. 20, 3D GRAPHS


7
0 i kopykitab.com/in + m •••

DJ Notes '"t • 21 ...;if 1)9+ ).

S.Y.B.Sc.(Computer Science) Python Programming Language n

Note that,

• plt. xlabel (), pl t. ylabel () is used to label the x-axis and y-axis, respectively.

• plt. title() is used 10 provide title 10 the graph.

lwo lines on Qme graph•

lJ,O US lSO US
......
100 2-25 lSO 275 300

Fig. 1.8 : Line Graph

1.3.2 Bar graphs


A bar graph or a bar chart is a graph used to present categorical data with heights or lengths
proportional to the frequency distribution that they represent. As discussed it used to represent
data which is in terms of category or labels.

Pune Murnbl1
.,.,.,
~pur ....,_ Set••
Fig. 1.9 : Bar Graph

CHAPTER I. 20. 30 GRAPHS


S.Y.B.Sc.(Computer Science) Python Programming Language D

Refer the following code,

import matplotlib.pyplot as plt


left= (1, 2, 3, 4, 5]
height= (5, 24, 45, 32, 15]
tick....label = ['Pune', 'Mumbai', 'Nagpur', 'Nasik', 'Satara']
plt.bar(left, height , tick....label = ticlLlabel,
width= &.8, color= ['red' , 'green'])
plt . xlabel('cities')
plt.ylabel( ' No of Covid patients(in thousands)')
plt.title('Covid- 19 data')
plt.show()
See the Fig. 1.9 for its bar graph.

1.3.3 Histogram
A histogram is usually used to represent approximate distribution of numerical data. To construct
a histogram the range of values is usually divided in to non-overlapping intervals called as bins.
The number of values corresponding to each bin are noted and bars are drawn corresponding to the
number of values in each bin. The bins must be adjacent and are often equal in sire. As discussed,
it is used to describe numerical data which is given in a set of raw values.

Fig. 1.10 : Histogram

Refer the following code to draw the Histogram;

9 CHAPTER J. 20, 30 GRAPHS


S .Y.B.Sc.(Computer Science) Python Programming Language D

ges = [2,S,78,4&,3&,45,58,45,43 , 4&,44,


68,7,13 , 57,18,9&,77,32,21,2&,4&,45,32,38]
range = (&, 188)
bins= S
plt . bist(ages, bins, range, color= 'blue',
bisttype ='bar', rwidtb = &.8)
plt . xlabel('age')
plt.ylabel('No. of people')
plt.title('bistogram plot')
plt.sbow()

1.3.4 Pie chart


A Pie chart is a circular statistical graph which is divided in to slices the arc length of each is
proprtional to the frequecncy corresponding to the label. It is used to represent category data
which is given in terms of labels.
import matplotlib.pyplot as plt
left= [1, 2, 3, 4, SJ
height = [S, 24, 45, 32, 15)
tick_label = ['Pwle', 'Mumbai', ' Nagpur', 'Nasik', 'Satara'J
fig= plt.figure(figsize =(1&, 7))
plt.pie(height, labels= tick_label)
plt .sbow()

Fig. l .11 : Pie Chart

10 CHAPTER I. 2D, 3D GRAPHS


S. Y.B.Sc.(Computer Science) Python Programming Language Il

1.3.S Scatter plots


A scatter plot is used to identify a relationship between 2 numerical variables. Each member of
the data set gets plotted as a point with x y co-ordinates relates to its values for the two variables.

import matplotlib. pyplot as plt


girl s_scores = [81, 98, 78, 89, 188, 88, 98, 188, 88, 34)
boys_scores = (38, 29, 49, 48, 188 , 48 , 34, 45 , 28, 38)
gr ades_r ange = [18 , 28, 38, 48, 58, 68 , 78, 88, 98, 188)
f ig=plt .figure()
ax=fi g . adcLaxes([8 ,8,1, l) )
ax. scatt er(gr ades__range, girls_scores, col or= ' r')
ax . scatter(grades__range, boys_scor es, col or='b ' )
ax . seLxlabel('Grades Range')
ax . set _ylabel('Grades Scored')
ax . set_titl e('scatter pl ot')
plt . show()

scatter plo<
100
• •
90
• • •
80 • • •
i
JO

,)!
r,o

) 50
• • • •
«>

JJ
• •

••
20 •
20 «> r,o 80 IDO
Gr-.Rongo

Fig. 1. 12 : Scatter Plot

1.4 Three dimensional Points and Lines


Three dimensional plots are enabled by importing the mplot3d-toolk it which is included with the
main matplotlib installation;

II CHAPTER I. 20, 30 GRAPHS


S.Y.B.Sc.(Computer Science) Python Programming Language IT

from mpl_toolkits import mplot3d

Once this submodule is imported, a three-dimensional axes can be created by passing the
keyword projection=' 3d' to any of the normal axes creation procedure;

import numpy as np
import matplotlib.pyplot as plt
fig= plt.figure()
ax= plt.axes(projection='3d')

Once we run this code we get the 3 dimensional axis as follows:

10
08
06
04
01
00

1n

Fig. I. 13 : 3D Axes

The basic three dimensional plot is a line or a scaner plot created using (x. y, z) triples. Note
that,

• ax. plot3D function is used to create lines.


• ax. scatter3D function is used to create three dimensional scattered points.

The following code plots lines in 3D connecting points which lie on a circular helix (spring).
Note that the co-ordinates on this helix are given by (sin /, cos I , t) , t ER.

import numpy as np
import matplotlib . pyplot as plt
zvalue = np.linspace(&, 15, 18)
xvalue = np.sin(zvalue)
yvalue = np.cos(zvalue)
ax.plot3D(xvalue, yvalue, zvalue, 'red')

12 CHAPTER I. 2D, 3D GRAPHS


S.Y.B.Sc.(Computer Science) Python Programming Language Il

14
u
10
8
6
4
2
0

- 1.Q@~ ~ 26
oq, 2~ sq, 75i_oo
Fig. l.14: 3D Helix

Similarly points in 3D can be plotted. The following examples plots points which lie on a
circular helix (spring). Note that the coordinates on this helix are given by (sin t. cost. t).

import numpy as np
import matplotlib.pyplot as plt
from mpLtoolkits import mplot3d
ax= plt.axes(projection='3d')
zvalue = np.linspace(&, 15, S&)
xvalue = np.sin(zvalue)
yvalue = np.cos(zvalue)
ax.scatter3D(xvalue, yvalue, zvalue, c=zvalue,cmap='Greens')

• • •• 14
u
• • •• '
~
10
8
6
• • •• • 4
2
0

~
-1 °'-~-~2i OQ».2~ sq, 7~oo - 1.

Fig. l.15 : Plot of points on 3D Helix

13 CHAPTER l. 20, 30 GRAPHS


[I] Notes --- ~ 27 ~ f 69+ ~

S.Y.B.Sc.(Com puter Science) Python Programming Language n

1.5 Three dimensional contour plots


Analogus to the two dimension contour plots mplot3d contains tools to create three dimensional
surface plots using the same inputs.
Consider the example to plot a 2-dimensional Gaussian distribution which has an equation of
the fonn

where. - 2 S x ~ 2. -2 ~ y ~ 2.

import numpy as np
import matplotlib . pyplot as plt
from mpl_toolk its import mplot3d
def f (x , y) :
r etunt np.exp(-x**2 - y**2)
x = np.linspac e(- 2, 2, 188)
y = np.linspac e(- 2, 2, 188)
X, Y = np.meshgr id(x, y)
Z = f(X, Y)
fig= plt . figure()
ax= plt.axes(p rojection= ' 3d ' )
ax.contour3D(X, Y, Z, S8 , cmap=' RdBu')
ax.set_xla bel('x')
ax.set_yl abel('y')
ax.set_zl abel('z')

08
06
o•
Q2

-=--=-,,,; f0
8~6
-20..1~1«1-0 -sg y
500 OS 10
I 15 20
-1-5
-20

Fig. 1. 16 : 3D Contour Plot of e-<x1+y2)

CHAPTER I. 20, J D GRAPHS


14
S.Y.B.Sc.(Computer Science) Python Programming Language D

1.6 Wireframes and Surface plots


1\vo other types of three-dimensional plots that work on data which is in a grid format are
wireframes and surface plots. These take a grid of values and project it onto the specified three-
dimensional surface, and can make the resulting three-dimensional forms quite easy to visualize.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
def f(x, y):
return np.exp(- x**2 - y**2)
x = np.linspace(- 2, 2, 188)
y = np.linspace(-2, 2, 188)
X, Y = np.meshgrid(x, y)
Z = f(X , Y)
fig= plt.figure()
ax= plt.axes(projection='3d')
ax.plot_wireframe(X, Y, Z, color='blue')
ax .set_title('wireframe plot');

w reframe

0.8
06
04
02

-2-0.-15-1.~
soo os 10
15 20
Fig. 1.17: Wireframe plot for f (x,y) = e-(z2+,2)

A surface plot is like a wireframe plot, but each face of the wireframe is a filled polygon.
Adding a colormap to the filled polygons can aid perception of the topology of the surface being
visualized.

15 CHAPTER l. 20. 3D GRAPHS


S.Y.B.Sc.(Computer Science) Python Programming Language IT

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
def f(x, y):
return np.exp(-x**2 - y**2)
x = np.linspace(- 2, 2, 199)
y = np.linspace(-2, 2, 199)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
ax= plt . axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=l, cstride=l,
cmap='viridis', edgecolor='none')
ax.set_title('Gaussian')
Gaussian

08
06
04
02

-2 a_, !°l-111-0
Soo OS LO
LS 20

Fig. 1. 18 : Surface plot of Gua-;sian J(x, y) = e-Cxl+y2)

1.7 Surface Triangulations


The triangulation of a paramterically defined surface is simply achieved by triangulating the area
of definition. (or simply dividing the area in to triangles). However the triangles may vary in shape
and extension in object space, posing a potential drawback. This can be minimized by adaptive
methods while considering the step width while triangulating the parameter area. ThJs can be very
useful technique if the grid is not evenly spaced.
Consider the surface z =J(x , y) =x! + y2 defined on -3 s x ~ 3, -3 s y s 3.
The surface triangulations can be obtained using the ax. plot_tri surf which creates a
surface by first finding a set of triangles formed by adjacent points.

16 CHAPTER I. 20. 30 GRAPHS


S.Y.B .Sc.(Computer Science) Python Programming Language II

Refer the code below;


import numpy as np
import matplotlib. pyplot as plt
from mpl_toolkits import mplot3d
def f(x , y):
return x**2 + y**2
x = np . random .unifonn(low=- 3, high=3, size=(l&&))
y = np . random .uniform(low=-3, bigh=3, size=(l&&))
z = f(x , y)
ax = plt. axes(projection='3d')
ax.plot_trisurf(x, y , z,
cmap='viridis ' , edgecolor='none ' )
Note that,
• np. random. unifonn() draws a random sample from uniform distribution on the interval
f-3, 3).

14
12
IO
8
6
4
2

2 3
0 1
-1
-2
J -3
Fig. 1.19 : Surface Triangulation of / (x , y) "' x2 + y2

1.8 Self Exercises


I. Plot the following functions:

17 CHAPTER I. 20. 3D GRAPHS


S.Y.B.Sc.(Computer Science) Python Programming Language TI

(a) /(x) = sin2x,x E [-1r/2,,r/2] (i) f (x) = e - 1/x


(b) /(x)=cos(x+ l},xE [0,,r] (j) /(x) = e l/zl
(c) f(x) = 2x,x E [- IO, 20]
(k) f (x) = ~
(d) f (x) = logt' x.x E [O, 20]
(e) /(x) = tr,x E [O, IO] 0) J (x) = e-zl
(f) /(x) = tanx,x E [- ,r/2.,r/21 tr - e-x
(m) /(x) = sinbx =
(g) f(x) = sin(x + 2),x E [0,2,r] 2
tr + e-x
(b) / (x) = e l/x (n) /(x) =cosh x = 2
2. Sketch the graph of the following functions:

(a) /(x) = sio- 1(x + l),x E [-2, 0] (d) / (x) = sinb- 1 x, x E [-10, 10)
(b) /(x) = cos- 1 x {e) /(x) = cosh- x,x 1
E [I , JO]
(c) f(x) = tan- 1 x,x E [-,r/2,n'/21 (f) f (x) = cos- 1 (x2 )

3. Plot graphs of the following:

(a) / (x) = ~+I (g) / (x) = lxl


(b) /(x) = cos(tr)
(h) /(x) = lxl +Ix + II
(c) f(x) = log 10(x 2 + l),x E [-10, 25]
(i) /{x) = lx2 - ll
(d) f (x) = esinx, x E [0, 20]
(e) f(x) = x 3 + l (j) /(x) = l +x + x2
(f) f (x) = xl/2 I
(k) /(x) = -,x E (0, 10)
X

4. Plot the graphs of the following functions:

(a) / (x) = e2x + sio2 x + 3x2


(e) f(x) = {xsin(l/x) 2
if x :t- O
(b) f(x) = sin x 0 if X = 0.
X

if X ;fa 0
(f) /(x) = {x sin( l /x
2 2
) ~fx ,ta O
(c) f(x) = {~ sin( l /x) 0 if X = 0.
if X = 0.
x2 + 2 if O < X < 5
(d) /(x) = sin(l /x) (g) f (x) = ~ if 5 ~ x < IO
{
smx if x ~ 10 < 15.
18
CHAPTER l. 20, 3D GRAPHS
S.Y.B.Sc.(Computer Science) Python Prograrnmjng Language II

5. Sketch the graphs of the following functions:

(a)f1(x,y) =l (e) fs (x , y) = 2x + 3y
(b) fi(x,y)=:c (f) f6(X , y) = X2 + y2

(c) /J(x,y) = y (g) h(x,y) =x2 - y2


(d) f4(x,y )= x+y (h) fs(x,y)= ✓x2 +y2.

6. Sket.ch the graph of g1 (x, y) = y2,gi(x,y) = sin x.


7. Sketch the region :
R1 = { (x,y): x + y 5 1,x ~ 0, y ~ 0},
R2 = {(x , y) : 0 < x 2 + y 2 $ I},
R3 = {(x,y): I < xy < 2} in R 2.

8. Sketch the following regions in R3 :


R1 = {(x, y, z) : x 2 + y2 + z2 ~ I}
R2 ={ (x.y,z):05xS1.05y51,05 zS I}.

9. Sketch the following level curves:

(a) f(x, y) =x 2 + y2 , c =0, 1, 2, 3, IO, 100.


(b) f(x,y) =x+y,c = -1,2,3,5.

(c) f (x,y) = 4..jl - ~- f.c = 0, I, 2, 3, 4.


(d) f(x, y) = xy. c = -2, - 1, 0, I, 2, 3.

I 0. Plot Contours for the following functions:

(a) J(x,y) = y- x (g) z = sin(xy)


(b) f(x ,y) = ✓y-x (h) z =~cosy
2
(c) J(x , y) = 3x 2 + 5y (i) z = sin(x - y)

(d) f(x, y) = y2 (i) z = sin x - sin y


X
2 • (k) z = ( I - x 2)(1- y 2 )
(e) e-<x +y-} x-y
1 (1) z = 2 2.
(f) f(x, y) = sin- (y -x) 1 +x +y

19 CHAPTER I. 20, 30 GRAPHS


S.Y.B.Sc.(Computer Science)
Python Programming Language n

11 . Draw the Histogram for the following data:

Subject Maths Science En.g lish Marathi Hindi


Passing Percentage 68 90 70 95 91
12. Draw the Histogram for the following data:
City Pune Mumbai Nasik Nagpur Aurangabad
Air Qality Index 168 190 170 195 191
13. Draw the pi chart for the following data:
Grain Wheat Bajra Rice Maize
Percentage of Total Production 23
Jowar Others
25 22 15 11 4

□□□

20 CHAPTER I. 20. 30 GRAPHS


Chapter 2

Computational Geometry

2.1 Points
The plane R.2 = R. x R. is referred as the
Euclidean plane. The point refers to posit
Euclidean plane. ion in the

2.1. 1 Point class


We will represent point as a Pytho n class with
two attributes x and y that will be usually of
class. If needed we can also use the floating integer
point representation to repre sent the two attrib
In this python class functions are written utes.
to initialize, return values of xy co-ordina
substract, multiply, divide, round off-values tes, add,
of the points along with formatting the displ
points. Objects of this points class are creat ay of the
ed and the operations can be performed.
code below; Refe r the

clas s Poin t:
def _ init _(s elf, x=&, y=&):
self . _x = x
self . _y = y

def x(se lf):


retu rn self .__x

def y(se lf) :


retu rn self ._y

21

S.Y.B .Sc.(C ompu tcr Scien ce)


Python Programming Lang uage TT

def _eq __( self , p):


retu rn (sel f.x == p.x) and (sel f.y = p .y)
def __ne_(self, p):
S.Y.B.Sc.(Computer Science) Python Programming Language II

def _e~(self, p):


return (self.x = p.x) and (self.y = p.y)

def __ne_(self, p):


return (self.x != p.x) or (self.y != p.y)

def _add__(self, p):


return Point(self.x + p.x, self.y + p.y)

def _sub_(self, p):


return Point(self.x - p.x, self.y - p . y)

def _JIIUl_(self, p) :
return Point(self.x * p.x, self.y * p.y)

def _truediv_(self, p):


return Point(self.x/p . x, self.y/p.y)

def __liash__(self):
return hash((self.x, self.y))

def _iter_(self):
return iter((self. x, self. y))

def _str_(self):
return "({},{})" .format (self.x, self.y)

def __repr_(self):
return "Point({ !r}, { !r})" .format(self.x, self.y)

def roundXY(self):
return Point(round(self.x), round(self.y))
For example one can check the following operations and verify the answers:
ql=Point(16l, 1)
q2=Point(12, 1)

22 CHAPTER 2. COMPlITATIONAL GEOMETRY


••
0 i kopykitab.com/in + (I) •

[I] Notes ~ ~ 36 ~ f 69+ ))

S.Y.B.Sc.(Computer Science) Python Programming Language TI

q3=Point (18, 1)
q4=point(18.SS,12.SS)
ql==q3 #this returns true
q2l=q3 #this returns false
ql+q2 #this returns (22,2)
ql~q3 #this returns (188,1)
ro\ll\dXY(l&.SS,12.SS) #this returns (11,13)

2.1.2 Euclidean distance between points


The distance between 2 points (x 1, yi) and (x2, y2) in the Euclidean plane R2 is given by

For calculating the distance in python refer the following code;

import math
def distance(ql, q2):
return math.hypot(q2 . x - ql.x, q2.y - ql .y)
ql=Point(18, 1)
q2=Point(12, 1)
distance(ql,q2) #returns 2

2.1.3 List of points: PointList class


The PoinlList class will hold a list of points. This class consists of various functions that will help
us initialize, copy, roundoff, append, remove the list along with some additional functions that will
help us return certain point and check whether the list contains a certain point.
Note that before the PoinlList class is written, Point class needs to be defined earlier. Refer the
code below;

class PointList:
def _init_(self, *args):
if type(args[8]) is Point:
self.points= list(args)
elif type(args[8]) is tuple:
self.points= [Point(t[8], t[l]) fort in args]
elif type(args[8]) is list:

23 CHAPTER 2. COMPtrrATIONAL GEOMETRY


S.Y.B.Sc.(Computer Science) Python Programming Language n

self.points= list(args[8])
else:
raise ValueError("Please check your argments.")

def copy(self):
return copy.deepcopy(self)

def _len_(self):
return len(self.points)

def _eq_(self, ql):


if len(self.points) ! = len(ql . points):
return False
for i,q in enumerate(self.points):
if q != ql.points[i]:
return False
re·turn True

def _iter_(self):
return iter(self.points)

de£ _ getitem,__(self, i):


if isinstance(i , slice):
return type(self)(self.points[i])
elif isinstance(i, int):
return self.points[i]

def _ contains_(self, q) :
for pt in self.points:
if pt= q : return True
return False

def roundPoints(self):
return PointList([q.roundXY() for q in self.points])

def append(self, q):


self.points.append(q)

24 CHAPTER 2. COMPUTATIONAL GEOMETRY


Python Programming Lang uage ll
S.Y.B.Sc.(C ompu ter Science)

def appe ndA ll(se lf, plis t):


for q in plis t:
self .app end (q)

def rem ove( self, q):


self .poi nts. rem ove (q)

def rem oveA ll(se lf, plis t):


for q in plis t:
self .rem ove( p)

In the code above see that the _ini t_ () is the cons


tructor of the class and it can take several
inputs.
For example,

• If the input is a tuple,

qll = Poi ntL ist( (l,1 ),(2 ,5), (4,6 ),(7 ,9))
qll

The output is,


oint (7,9 ))
Poin tLis t(Po int( l,1) ,Poi nt(2 ,3), Poin t(4, 6),P

,
• Uthe input is a tuple of objects of the point cJass

, Poi nt(l ,7))


ql2 = Poin tLis t(Po int( 4,S) , Poi nt(l l,8)
q12

The output is,

Poi ntL ist( Poi nt(4 ,5), Poi nt(l l,8) ,Poi nt(l ,7))

• If the input is a list of points,

2S CHAPTER 2. COMPUTATIONAL GEOME'JRY


[I] N ot es

-.
"'II .
... , 39 ·Q _J _
..Q f I) ~ >>

S.Y.B. Sc.{Com put er Scienc Python Programrriing La


e) ng uag e TI

ql 3 = Po in tL ist ([P oi nt ( 4 9 )
, , Po in t(l 9, 8) , Po in t(l ,7 )] )
ql 3
The output is.
Po in tL ist (P oi nt (4 ,5 ) ,P
oi nt (l& ,8 ),P oi nt (l, 7) )
Various other operations can
be perfomed as follows:
ql l.a pp en d( Po in t(S ,8)
)
ql 2. re m ov e( Po in t(l l,8
))
ql 3. re m ov eA ll( (P oi nt
(4 ,5 ),P oi nt (l ,7 )) )

2.1.4 In te ge r Point Li sts


One can convert a list wi
th floating point values to
method in the PoinlList cla a list with integer us ing
ss. Refer the co de below; the rou nd Po ints()
flo at lis t=Po in tL ist ((2
. 25 , 3.1 41 ) , (5 .5 7, 4.
in te ge rli st=flo at lis t.r 29 ), (6 .8 , 8. 9) )
oW \d Po in ts( )
in te ge rli st
lt approximates it wi th a
value ±0.5. The output is
as follows;
Po in tL ist (P oi nt (2 ,3 ),P
oi nt (6 ,4 ),P oi nt (7 ,9 ))

2.1.S Ordered Point Sets


This means a list of points
in which there are no dupli
Points as keys which in tur cates. This is do ne us ing
n automatically removes Or de red Di ct using
PointList Class must be pre the duplicates. No te tha
defined. Al so we need to t Po int Cl ass an d
collections. This return s an import the OrderedDict cla
object of the type set. ss predefined in
from co lle ct io ns im po
rt Or de re dD ict
cl as s Or de re dS et Po in
t(P oi nt lis t):
de f _ in it_ (s el f, *a
rg s) :
Po in tL is t._ in it_ (s el
f, *a rg s)
se lf. po in ts = lis t(O rd
pr in t(O rd er ed Se tP oi nt er ed Di ct .fr om ke ys (s
((l ,2 ), (3 ,7 ), ( 2, 9) , el f.p oi nt s) )
(1 ,2 )) )
Ve rify that the output is as fol
lows;
(( 1, 2) ,(3 ,7 ),( 2, 9) )

26
CHAPTER 2. COMP\IT
ATIONAL GE OM ETRY
S.Y.B.Sc.(Computer Science) Python Programming Language n

2.1.6 Extreme Points


An extreme point of a point list is a point that is at a greatest distance along a given direction.
We define a algortibm which determines the extreme points in the X and Y directions. On the
X-axis the exterme polnts will lie to lhe right extreme and the left extreme whereas on the Y-axis
the extreme points will always lie on the top extenne and the bottom extreme. For any given set
of points in a point list the number of extreme points will alaways lie between 2 and 4. Also note
that a Pointlist class needs to predefined ,earlier. Refer the Python code below

def extremePoints(qlist):
rightex = leftex = topex = bottomex = qlist[8];
for q in qlist:
if (q.x > rightex.x): rightex = q
if (q.y > topex.y): tope.x = q
if (q.x < leftex.x): leftex = q
if (q.y < bottomex.y): bottomex = q
return PointList([rightex, topex, leftex, bottomex])
The above function returns a polnt list. Consider the following example;

extremePoints([Point(-1,-S), Point(2,-2),
Point(-4,-4), Point(2,l), Point(2,2),Point(-S,S),Point(6,6)])
The output will be as follows
PointList(Point(6,6),Point(6,6),Point(- S,5),Point(-1,-5))

2.1.7 Random Set of Points not in any General Position


A set of points are said to be in a general position if no three points are comnear. A lot of algorithms
in Computational Geometry require the input as a Random set of points.
The algorithm will generate points on a II x n grid where there is a point on each intersection
2
of the grid. Note that the maximum number of points in such a grid can be n .. .
The following is a simple algorithm for a generating set Q of m random pomts on a n x n gnd
that ranges from min to max on the ranges of X and Y.

1 Let Q = ? (empty set)

2 Repeat while IQI < m


2.1 Generate a point q = (x,y)

CHAPTER 2. COMPlJrATIONAL GEOMETRY


27
S. Y.B.Sc.(Computer Science) Python Programming Language Tl

2.2 Q=QU{q }

Note that, min ~ x, y 5 max, and m 5 n 2•


This algorithm is fast but does not guarantee the points to be in general position.
In the function below we restrict our va1ues of the co-ordinates x, y to lie in [-6, 6J so that a at
a maximum 144 points can be generated. Refer the code below;
import random
def randomPointSetNongeneral(numberOfPoints, lower=-6, upper=6):
maxNumberOfPoints = (upper - lower+ 1)**2
numberOfPoints = min(maxHumberOfPoints, numberOfPoints)
randomPts = set()
while len(rando mPts) < nwnberOfPoints:
q = Point(ran dom.rand int(lower , upper),
random. randint (lower, upper))
randomPt s.add(q)
return list(rando mPts)
We generate 3 random points as below

randomPo intSetNon general(3 )

2.2 Displaying points and other Geometrical Objects


In this section we first write down a Canvas class that provides us a blank Canvas wbich we use
to draw. Then functions are written as and when we want to draw geometrical objects on this
canvas. These functions will provide an easy interface to needed parts in PyPlot. The combination
of Canvas and the set of functions will serve our purpose as a Graphic Language
Our Graphic Language will provide light weight wrapper that passess the keyword arguments
(**kwacgs) to the PyPlot functions.
Refer the code below to create the Canvas;

CANVAS_WIDTH=8
CANVASJiEIGHT=8
import matplotl ib.pyplot as plt
class Canvas:
def _init_( self, title, xlabel='X ', ylabel='Y ',
ql=Point (- 8, -8), q2=Point( 8, 8)):

28 CHAPTER 2. COMPlJTATIONAL GEOMETRY


0 i kopykitab.com/in + m ••

[I] Notes • • 42 ~ f 69+ >>

S.Y.B.Sc.(Computcr Science) Python Programming Language II

self.fig= plt.figu.re()
self.fig.set_size_inches(CANVAS_WIDTH, CANVASJ{EIGHT)
self.ax= self.fig.ad<Lsubplot(lll, aspect='equal')
plt.ti tle(title)
plt.xlabel(xlabel)
plt. ylabel(ylabel)
plt.xticks(range(ql.x, q2 . x))
plt.yticks(range(ql . y, q2.y))
self.ax.grid(True)
self.ax . set_xlim([ql . x, q2 .x])
self. ax.set_ylim([ql.y , q2.y])

def sbow(self):
plt.show()
plt. clfO
plt.cla()
pl t . close()
And then execute a demo Canvas as follows;
def demoCanvas():
Canvas(title="This is our starting canvas").show()
demoCanvas ()

!j

-_1, 1-
jj
Fig. 2. 1 : Canvas

CHAYTER 2. COMPlITATIONAL GEOMETRY


29
S.Y.B.Sc.(Computer Science) Python Programming Language n

Below we will illustrate some functions to draw on this canvas.


• Use filled circle O to draw a filled circle about a given point.

impor t matpl otlib. pyplo t as plt


def filled circle (gc, pt, radius =l, **kwargs) :
gc.ax. adcLp atch(p lt.Circ le((pt .x, pt.y) , radiu s, **kwargs))

The above functio n defined will add a circular patch about the given point
of a given radius.
Make sure that the point class is predefined caruer. Refer to the code below;

ql=Po int(8, 8)
gc=Canvas("Filled Circle Demo")
fill edcirc le(gc, ql)

Filled Circle o.mo

-l

-2

-3

-4
0


-7

--8 +--.--.- -,---.-- --,---,- ....--,-- -,..---.- ,--..--.. ..--,--- ,..--'


--8 -7 -6 ➔ -4 -3 -2 -l O 1 2 3 4 5 6 7
X

Fig. 2.2 : Filled Circle on Canvas

30 CHAPTER 2. COMPUTATIONAL GEOMETRY


Python Progra mmin g Langu age IT
S.Y.B.Sc.(Computcr Science)

segm ent between any two given


• The functi on line2 poin tsO will help us draw a line
points on our Canvas.

impo rt matp lotli b . pypl ot as plt


def line2 poin ts(gc , ql, q2, **kwargs ):
gc . ax. adcLpatch (plt . arrow (ql . x , ql.y ,
q2.x - ql.x , q2.y - ql . y, **kwargs) )

s (0, 0) and (5, 5) on our canvas.


Suppo se we wish to draw a line segment betwe en two point
Refer the code below;

ql=P oint( 8, 8)
q2=P oint( S, 5)
gc=Canvas("L ine Segment between 2 poi nts ")
line 2poin ts(g c,ql, q2)

i.- S.V,,-C ~ - 2 points

► 0

-I

-1

-)

-1

':'-_"'.;'7--4
...... ➔---:
--:-"": l--
_l:--,-l:--,O---:l-l-
_3---:
_.---: , - S - ,- 1-
1

Fig. 2.3 : Line segment on Canvas

31 CHAPTER 2. COMP UTATIONAL GEOMETRY


S.Y.B.Sc.(Computer Science) Python Programming Language II

2.2.1 Line, Rays and Line Segments


Below are some definitions which will useful ahead in understanding certain concepts.

1. Line : A straight one dimensional figure having no thickness and extending infinitely in both
the directions.

2. Ray : A straight one dimensional figure having no thickness, begining at a point and
extending ilnfinitely in one direction.

3. Line Segment : A straight one dimensional figure begining at a point and ending at a point.

4. Euclidean Plane : A flat surface or R2 as defined earlier.

5. Half Plane : A Planer reigon consisting of all points on one side of an infinite straight line
and no points on the other side.

( a) Closed Half Plane : a half plane that includes points on that line.
(b) Open Half Plane: a half plane that does not include points on that line.

6. General position of llnes: a set of lines is said to be in a general position if no three of them
are concurrent (intersect at the same point).

7. Vertex : Toe common endpoint of two or more rays or line segments.

For most of the algorithms, the direction of the rays or line segment is important.
The following code demonstrates how to travel from a point to another point with the direction
parallel to X and Y-a.xes.

def LineSegments():
ql = Point (1, 1)
q2 = Point(4,4)
gc = Canvas("Geometry of line segments", pl=Point(&,&), q2=Point(7,6))
filledcirc l e(gc, ql)
filledcircl e(gc, q2)
line2points(cgc ,pl ,Point(q2 .x, ql. y), color="red")
line2points(cgc,p2,Point(q2.x, ql.y), color="red")
gc.show()
Line Segments()

32 CHAPTER 2. COMPUTATIONAL GEOMETRY


S.Y.B.Sc.(Computer Science) Python Programming Language IT

Geometry of hne seqments

► J

0 i -- - - -~ --.....----~-----,...------,----'
0 6
X

Fig. 2.4 : Pathe from one point to another


Some more functions to implement Geometrical tasks like,
• calculating the length of the point from the origin

• the vector from point p I to P2

• returning the sine and cosine of the angle between the points p I and p2

• calculating unit vector from a point p I to P2

• calculating the mid-point of the line joining p I and P2,


can also be written. We demonstrate two functions;
def vector(ql, q2):
return q2 - ql
The above function will help us determinng the vector from q1 to qi. Similarly,
def midpoint(ql, q2):
return ql + (q2 - ql)/Point(2,2)
will help us in computing the mid-point of the line joining q I and q2.

33 CHAPTER 2. COMPUTATIONAL GEOMETRY


+ m

••
0 i kopykitab.com/in
))
.. l, 47 ..i f 1S9+
CI] Notes

ge IT
Python Prog ramming Langua
)
S. Y.B.Sc.(Computer Science

ys and Line Segements


2.2.2 Displaying Lines, Ra
As disc ussed earlier
in both the directions.
• A line passes through q I
and q 2 and extends to infi nity
infinity.
passes through the point q 2 to
• A ray begins at point q I and
and ends at q 2 •
• A line segment begins at q 1
our earlier sections. We now
lo construct a line segment in
We have already discussed how a given pair of points.
ct rays and line passing through
coocentrnte on how to constru leng th of a line segment pa~sing
through two points
a fun ction 10 extend the
First let us write
q , and q2.

de f qS in( ql, q2 ):
dis tan ce( ql, q2)
ret un i (q2 .y - ql . y) /
de f qC os( ql, q2 ):
dis tan ce (ql , q2)
ret un i (q2 .x - ql . x) /
de f ex ten d(q l,q 2,l ):
ql .x
x = 1 * qC os( ql, q2) +
l * qS in( ql, q2) + ql .y
y =
ret un i [ql , Po int (x, y)]
line
the task of constructing the
oin ts( ) function which has
Now we will use the lin e2p .
the ray and the line in general
segment to further constru ct
wargs):
de f ray (gc , ql, q2, **k
if ql != q2:
end (ql , q2, 188 8)
po sln fl, po sln f2 = ext
fl, pos lnf 2, **kwargs)
lin e2p oin ts( gc, po sln
from
nts ( I, I) and (3, 3) starting
w a ray passing through the poi
Now suppose we want to dra
the point (I, I).

ql= Po int (1, 1)


q2= Po int (3, 3) q2= Po int (7, 6))
of ray ", ql= Po int (8, 8),
gc = Can vas ("G eom etry
ray (gc ,ql ,q2 )

NAL GEOMETRY
CHAPTER 2. COMPUTATIO
34
[I] Notes "t • 48 ~ f ij9+

S.Y.B.Sc.(Computer Science) Python Programming Language n

Geometry ol r.,y

► l

Fig. 2.5 :Ray

Similarly, we can construct an infnite line which extends in both the directions. Refer the code
below;

def line(gc, ql, q2, **kwargs):


if ql I= q2:
poslnfl, poslnf2 = extend(ql, q2, 188t)
neginfl, neglnf2 = extend(ql, q2, - 18t8)
line2points(gc, poslnfl, poslnf2, **kwargs)
line2points(gc, neglnfl, neglnf2, **kwargs)

Now suppose we want to construct a line segment passing through points (2, 2) and (4, 4).
ql=Point(2,2)
q2=Point(4,4)
gc = Canvas("Geometry of line segments", ql=Point(8,8), q2=Point(7,6))
line (gc , ql, q2)

35
CHAPTER2. COMPl!rATIONALGEOMEJRy
Python Programming Language n
S.Y.B.S c.(Computcr Science)

Geome uyolhn e

Fig. 2.6 : Line Segment

2.3 Polygons
ons:
Consider some basic definitions related with the polyg
or line segments meet.
I. Vertex: The point where two or more lines, rays
nce of points caJled vertices such that the
2. Polygonal chain : A curve speci fied by a seque
curve connects consecutive vertexes.
e first and last vertex are not con-
(a) Open Polygonal chain : A polygonal chain whos
nected.
(b) Closed Polygonal cbain : A polygonal chain
whose first and last vertex are connected.

where n ~ 3
Note that a polygonal chain bas vertexes v,, vz, ... , v,,

3. Edge : A line segment joining two vertexes.

36 CHAPTER 2. COMPllTATIONAL GEOMETRY


0 i kopykitab.com/in + 0 •••

[] Notes • ~ 50 ...Qf 1j9+ >>

S. Y.B.Sc.(Computer Science) Python Programming Language IT

4. Convex set : A set of points q 1, qz, ... , qn such that all the edges (q;, qf) for i, j :S n and
i -:;:. j lie in the set

5. Polygon : The rcigon bounded by closed curve. A polygon is closed planar polygonal chain.
6. Simple polygon : The reigon bounded by a simple(non-intersecting) closed curve.

7. Convex polygon : A simple polygon whose interior is a convex set.

8. Triangle : A triangle is a simple 3 sided convex polygon

2.3.1 Triangle
As mentioned earlier the triangle is a 3 sided convex polygon. Refer the code below;

def Triangle(cgc, qlist , labels=("a", "b", "c"), dot=False,


colors=("red", "green", "blue"), **kwargs):
a,b,c = qlist
line2points(gc, a , b, color=colors[9], **kwargs)
line2points (gc, b, c, color=colors[l], **kwargs)
line2points (gc, c, a, color=colors[2], **kwargs)

Now suppose we want to plot a triangle with vertices ( 1, 1), (4, 1) and ( 4, 4). Then refer the
code below;

LI

Fig. 2.7: Triangle

37 CHAPTER 2. COMPUTATIONAL GEOMETRY


S.Y.8.Sc.(Computer Science) Python Programming Language n

ql3 = Pointl ist([P oint(l ,l), Point( 4 , 1), Point( 4,4)])


gc = Canvas ("Trian gle ", ql=Poi nt(&,8 ), q2=Point (7,6))
Triang le(gc,q l3,dot= False)

2.3.2 Signed Area of a triangle


In Computational geometry computing the signed area of the triangle plays an importa
nt
role in many algorithms. Note that the signed area is positive if the vertices are
taken in
anticlockwise sense whereas the signed area is negative if the vertices are conside
red in a
clockwise sense.
The signed area of a triangle in 2D is given by

A(T) = ~ [::
Cx
: ::
Cy
!
1
] •

where I · I denote the detenninant of the matrix.


Also, ensure that the Point class is earlier written when calculating the Signed Area.
Refer
the code below;

import nwnpy as np
def triangl eArea (a, b, c):
determinant=np .linalg .det( [[a.x, a.y, 1],
[b .x, b.y, 1], [c.x, c.y, 1]])
return &.S*determinant

Now suppose we wish to calculate the area of a triangle with vertices at ( l , I), (1,
5) and
(4, 1). Refer the code below:

a = Point( l,1)
b = Point( l, S)
c = Point( 4,l)
area= triangl eArea( a, b, c)
area

38 CHAPTER 2.. COMPUTATIONAL GEOMETRY


S.Y.B.Sc.(Co mputer Science) Python Programming Language II

The area computed for the above triangle is

- S.999999999999997

Note that the above area is negative as the points are oriented in an anticlockwise sense.

2.3.3 Triangles and the relationships of points to the lines


lf we treat a triangle comprising of the line segment (a, b ) and a independent point c . then
the signed triangle area helps us identify a relationship between the point c and the line L
determined by the line segment.

(a) If the area of the triangle (a, b. c) > 0, then the point c is to the left of the Line Las
you travel from a to h. Otherwise it is to the right.
(b) lf the area of the triangle (a. b, c) ~ 0 then the point c is to the left of the line Lor
collinear with it.
(c) lf the area of the triangle (a. b , c) = 0 the point c is collinear with Line L

Here we define some functions to check the above task;

def Collinear (a, b, c):


return triangleA rea(a, b, c) = 8

def Left(a, b, c):


return triangleA rea(a, b, c) > 8

def LeftOn(a, b, c):


return triangleA rea(a, b, c) >= 8

def Right (a, b, c):


return not LeftOn(a, b, c)

def RigbtOn(a, b, c) :
return Left (a, b, c)

39 CHAPTER 2. COMPlITATIONAL GEOMETRY


IT
Python Pro gra mm ing Language
S. Y.B.Sc.{Computer Science)

elli ng fro m poi nt a to poi nt


ans the left ban d sid e wh ile trav
No te tha t the con ven tion left me
b. n a and b. By
to also test for bet wee n tha t is "do es the poi nt c tie " betwee
Fin ally, we wis h in the mid dle of the seg me nt
wee n it ess ent iall y me ans tha t the poi nt c is lyin g som ehw ere
bet
[a, b].
foll ow ing obs erv atio ns:
pro ble m we hav e con sid er the
No w for mu lati ng the above the
h the poi nts a and
bet wee n a and b. it is nec ess ary for c to be col line ar wjt
(a) For c to lie
b. seg me nt (a , b) nor
nt c mu st not be to the rig ht of the end poi nt b of the line
(b) the poi vic e-v ers a if you are
to the left of the of the end poi
nt a on the line seg me nt (a , b) or
con sid erin g the line seg me nt
(b, a)
5 hx or hx 5 Cz 5 Ox and
exp res sed as follows: ax 5 Cx
The sec ond con diti on can be
Ref er the cod e bel ow :
ay 5 cy 5 b y or by 5 cy 5 ay.

de f Between(a, b, c):
if no t isC oll ine ar( a, b, c):
ret urn Fa lse
or (b. x <= c.x <= a.x )) and
ret urn ((a .x <= c.x <= b.x )
y <= c.y <= a.y ))
((a .y <= c . y <= b.y ) or (b.
ctly lie wit h res pec t to the
ver ify usi ng the abo ve fun ctio ns wh ere does the poi nt exa
On e can
to the abo ve con diti ons .
sid e of a tria ngl e wit h res pec t

and reflection
2.4 1\vo dimensionaJ rotation
giv en as follows:
I ) The two dim ens ion al rota
tion ma trix wit h an ang le (J is

cos fJ sin /J]


ro t= [-si n(} cos(} ·

r clo ckw ise dire ctio n.


in [O, 2,rJ con sid ere d in cou nte
No te tha t the ang le O can var y
se arc som e of the
ens ion al refl ecti on ma tric es are giv en as follows. The
2) The two dim
spe cia lise d refl ect ion s.

L GEOMETRY
4-0 CHAPTER 2. COMPlJJ'ATIONA
S.Y.B.Sc.(Computer Science) Python Programming Language TI

• The reflection about the Y-axis is given by

refy = [ ~I ~] .

• The reflection about the X-axis is given by

• The reflection about the origin is given by refO = [ ~I ~I]

• The reflection about the line y =x is given by

refyx = f~ ~].
• The reflection about the line y = -xis given by

refymx = _ [01 -IJ


0
.

Refer the python code below to construct the two dimensional rotation matrix using numpy,

import numpy as np
import math
def rotation(xy, theta):
X, y = xy
radians=matb.radians(theta)
c, s = np.cos(radians), np.sin(radians)
j = np.matrix([[c, s], [-s, c]])
m = np.dot(j, [x, y])
return float(m.T[&J), float(m.T[l])
The rotation matrix defined above is used to rotate the point (I, 0) through an angle of 90
degrees in the anticlockwise sense.

tbeta=-9&
point = (1, 19)
rotation(point,theta)

41 CHAPTER 2. COMPUTATIONALGEOMETRY
S.Y.B.Sc.(Computer Science) Python Programming Language II

The output ls as follows

(6 . 123233995736766e-17, 1.&)
Similarly a reflection through the X-axis can be coded as follows:

import numpy as np
import math
def refx(xy):
x, y = xy
j = np.matrix([[l, &], [&, -1]])
m = np.dot(j, [x, y])
return float(m.T[&]), float(m.T[l])
The reflection matrix defined above is used to re.fleet the point (O, 1) through the X-axis;

point= (t, 1)
refx(point)
The output is as follows;

($.$, -1.&)

2.5 Three dimensional rotation and reflection


Unlike two dimensional rotations and reflections similar concepts are applicable with some changes
as there is an additional degree of freedom.

I. The rotation matrix in three dimensions is considered along a particular axis (or equivalently
in a corresponding plane) as follows;

• Rotation along the Z-axis (or equivalently rotation in the XY-plaue in anticlockwise
sense) is given by the matrix,

cos 0 sin0 Ol
Rotz = -s~n0
[ ~e ~.

42 CHAPTER 2. COMPlITATIONAL GEOMElRY


S.Y.B.Sc.(Computer Science) Python Programming Language D

• Rotation along the Y-axis (or equivalently rotation in the XZ-plane in anticlockwise
sense) is given by the matrix,

cos O O - sin Ol
Roty = 0 1 0 .
[ sinO O cosO

• Rotation along the X-axis (or equivalently rotation in the YZ-plane in anticlockwise

l
sense) is given by the matrix,

Rotx;::: 0
] cosO
osinO .
o
[0 -sinO cosO

2. As io the case of Rotation, reflection too is performed along a selected ax.is (or equivalently
reflections relative to a particular plane). We mention the matrices as the reflection relative
to a particular plane,
• The reflection relative to the XY-planc (or equivalently reflection through the z-axis)is
given by,

I
I O O l
Refz = O 1 O .
0 0 -]
• The reflection relative to the XZ-plane (or equivalently reflection through the Y-axis)
is given by,
1
Refz = 0 -I O .
o ol
1
0 0 I
• The reflection relative to the YZ-plane (or equivalently reflection through the X-axis)
is given by,

Refz = 0
-1 oI Ool .
[ 0 0 1

Refer the following code where define a rotation of a point about the Z-ax.is;

from scipy.spatial.transform import Rotation as R


def Rotz(v,theta):

CHAPTER 2. COMPl.JI'ATIONAL GEOMETRY


43
••
i kopykitab.com/in + 0 •

57 ...Qf 69+
[I] Notes .. •

Python Programming Language n


S.Y.B.Sc.(Computer Science)

radian s=ma th.rad ians(t heta)


c,s = np.co s(rad ians) , np .sin(r adian s)
r = R.from...matrix([[c, s, 8] , [ -s, c , 8] , [8, 8, l]J)
retur n r.app ly(v)
in the anticlokwise sense with
Now suppose we want to rotate the point f I, 0, OI about the Z-axis
an angle 90 degrees.

Rotz( [l,8,8 ),-98)


The Output will be as follows;
array ([$., 1. , 8.))
in the following manner;
Similarly. the reflection through the XY plane can be defined
from scipy .spati al.tra nsfoI 'lll import Rotat ion as R
def Refz( v):
)
r = R.frOIIUllatrix ( ([l, 8, 8) , (8 , 1, 8), (8 , 8,-1] )
retur n r.app ly(v)

Now suppose we want to rotate the point (0, 0, JJ through the


XY-planc,

Refz( [8,8, 1))


The result will be as follows:

array ( [ 8., 8., -1.])

2.6 Bezier Curve with Control Points


basis given by
A Bezier curve is a parametric curve that uses the Bernstein

to define a curve as a linear combination


n
B(s) = _L b j,n•VJ.
j=-0

44 CHAPTER 2. COMPlTTATIONAL GEOMETRY

I
•••
0 i kopykitab.com/in + 0
[I] Notes ~ '°' 58 ~ f ij9+ >>

S. Y.B.Sc.(Computer Science) Python Programming Language n

This comes from the fact that the weight of the sum is equal to one,

bo.,. + b1.,. + .... + b,,.,. =(s + (l - s))" =I.


This can be generalized to higher order by considering three, four etc. non-negative weights
that sum to one (in the above we have the two non-negative weights s and ( I - s).
Some features of the Bezier Curves are as follows:

• they can be easily used to model geometric objects like parametric curves, mangles.

• they can can be computed in an efficient and numerically stable way via de Casteljau's
algorithm.

• can utilize convex optimization techniques for many algorithms (such as curve-curve inter-
section), since curves (and triangles etc.) are convex combinations of the basis.

• lhey ald physical analysis using finite element methods (FEM) on isogeometric models by
using geometric shape functions called NURBS to represent data.

• they are used in robust control of dynamic systems; utilizes convexity to create a hull of
curves.

The bezier package in python will help us compute and visualise the bezier curve with a given
number of control points
Suppose we wish to construct a Bezier curve of degree 3 and with the 4 polygonal vertices
(I, 1), (2, 3), (4, 3) and (6, 4).

import numpy as np
import bezier
nodes2 = np.asfortranarray(( [l,2,4,6),(1 ,3,3,4)])
curve2 = bezier.Curve.fro11LJ1odes(nodes2)
curve2
The output is as follows

<Curve (degree=3, dimension=2)>

The bezier curve can also be visualised using seaborn package as follows;

45
CHAPTER 2. COMPUTATIONAL GEOME"raY
[I] Notes ~ ~ 59 ~ f 69+ >>

S.Y.8 .Sc.(Compute r Science) Python Programming Language Tl

35

30

25

20

IS

10
3 6
2
'
Fig. 2.8 : Bezier Curve

import seaborn
seaborn . set 0
ax = curve2 .plot(nUDL.pts=5)
The intersection points of the two bezier curves can also be determined. Refer the code below;

pointsl = np .asfortra narray([[ t.t, 8.5, 1.8),[8.8 , 1.t, 8 . 8)) )


cl = bezier.Cu rve(point sl, degree=2)
points2= np.asfortr anarray([ [8. 8, 8 .25, t.5, 8. 75, 1.8),[8.8 , 2.8 , -2 .8 , 2.8 , 6
c2 = bezier.Cu rve . frollL,Jlodes(points2)
intersect ion = cl . intersect( c2)
intersecti on
vals = np.asfort ranarray( intersecti ons[8, :])
vals
points3= cl .evaluate_ multi(val s)
points3
import seaborn
seaborn. set 0
ax= cl.plot(nu m_pts=25 6)
_ = c2.plot (nUJLpts=256, ax=ax)
lines= ax.plot( points3[8 , :], points3[1 , :],marker= "o", linestyle="None", color=
_ = ax.axis("s caled")
_ = ax . set_xlim( - 8.125, 1.15)
= ax.set_yli m(-8.8625 , 8.625)

46 CHAPTER2. COMPlfl'ATIONAL GEOMETRY


Python Prog ramm ing Language IT
S. Y.B.S c.(Compu ter Scie nce)

06
05
04

0.3

02

01

00
06 08 10
00 02 04

Fig. 2.9 : Intersection of 1\vo Bezier Curv es

2. 7 Sel f Exercises
two
Com pute the Eucl idea n dista nce betw een the
1. Consider two points ( I 0, 8) and ( I, 15) .
points.
ram
non- identical poin ts. Also writ e a Pyth on Prog
2. Create a Python PointList consisting of 5
ecutive poin ts in this list.
to find the Euclidean distance between the cons
Con vert
where the values are fl oatin g poin t valu es.
3. Create a Python PointList with 10 poin ts
thi s list to a integ er point list.
find
any general position on a 12 x 12 grid . AJso
4 . Generate a rand om set of IO poin ts not in
the extreme points along the X and Y axis.

5. Generate a rand om set of 5 points on a 12


x 12 grid. Plot thes e poin ts on canv as with a filled
circles of radius 0.4.
g the poin ts ( I, I) to ( 4, 7).
6. Draw a line segment on a canvas conn ectin
ts (1. I) to (4, 7).
7. Draw a line on a canvas conn ectin g the poin
poin t
poin ts ( I, I) and ( 4, 7) starting from the
8. Draw a ray on the canvas conn ectin g the
(4, 7).
the
and (4, 1) on the canv as and also calc ulate
9. Draw a triangle with verti ces (J , 1) , ( 1,5)
cloc kwis e sens e.
signed area in the cloc kwis e and the counter

47 CHAPTER 2. COMPlJl'ATIONAL GEOMETRY


i kopykitab.com/in + m ••

Notes ~ ~ 6 1 ~ f 69+

S.Y.B.Sc.(Computer Science) Python Programming Language 11

10. Draw a triangle with vertices at (2, 2), (2, 5) and (8, 2). AJso write down a Python program
to see if the point (3, 3) lies in the interior or exterior of the given triangle.

11. Draw a triangle with vertices ( I, I), (6, I) and ( I, 5). Write a Python program to see if the
triangle with these vertices is right angled.
12. Write a Python Program to rotate the point (2, 2) by an angle of 45 degrees in the clockwise
sense.
13. Write a Python Program to reflect the point (2, 2) through the X and the Y-axes respectively.

14. Write a Python program to rotate the point ( I, 2, 3) in the YZ-plane by an angle of 60
degrees.
15. Write a Python program to rotate the point ( 1,2,3) about the X-axis by an angle of 45
degrees.
16. Write a Python program to reflect the point (1, 2, 3) through the XY-planc.

17. Plot the Bczier curve with 4 control points ( l, 0), (3, 3), (6, 3) and (8, 1).

JS. Plot the Bezier curve with 3 control points ( l , 5), (3, I) and (7, 8)

19. Plot the Bezier curve with 6 control points {l , 2), (4, O), (8, 3), (5,4), (3, 3) and (6, 8)

20. Generate 5 random points on a 12 x 12 grid and connect them by line segments. Identify
whether they form a closed polygon.
ODD

CHAYTER2. COMPUTATIONALGEOMETRY
48
0 a kopykitab.com/in + m •••

62 ~ f 6 9 +
>>
N ot es ~ ~
[I]

Chapter 3
p e r a ti o n s Research in Python
S tu d y o f O

in Python
3.1 Linear Programming ue
obtain an op tim al val
op tim iza tion is a ma thematical method to ca se of a
Ll ne ar pro gra mm ing
or Li ne ar um value in
mi zal.io n pro ble m or finding the minim ble ms the
ca se of nuu:i onships. lnc ase of rea
l life pro
(max im um va lue in su bjected to lin ea r relal.i
ble m) wh ich are
minimization pro ho ld true.
nts are als o ass um ed to
no n-n ega tiv ity constrai o specific typ e of pro ble
ms which include,
on e de als wi th tw
M or e generally, tained by solvin g
de als wi th ma xim izi ng the profit to be ob
m usually
• Ma xim iza tio n pro ble
the pro ble m. ction while
wi th mi oimi7. ing the total co st of produ
m usu ally de als
• Minim12atlon pro ble
solving the proble m.

3.1.1 Basic Terminologies


sic thr ee co mp on ents;
ming models have ba
Al l the Li ne ar Program
,
we seek: to de ter mi ne
• De cis ion variables
we wish to optimize,
• Ob jec tiv e function
y.
• Constraints that the solution must sat isf
xtu re
e sp ec ial feed is a mi
es atl eas t 70 0 lb of sp ec ial feed da ily. Th
farm us
Problem 1: A ca ttle mp os iti on s,
ya be an wi th the following co
of wh ea t an d so
49

0 i kopykitab.com/in + 0 ••

• 63 ~ f 1S9+
>>
[1J Notes •

e JI
Python Programming Languag
S. Y.B.Sc.(Compuler Science)

Fib er cos t per lb)


Fee dstu tf Car boh ydr ates
0.0 9 0.02 0.2
whe at
0.6 0 0.06 0.8
soy abc an
of carb ohy drat es and atm ost 5 %
this special feed are atle ast 30%
The diet ary requ irem ents of feed mix .
imu m cos t of the
fiber. Det erm ine the dail y min
Problem Formu lati on:
to determine
I . Decision variables we see k
mod el are;
The decision vari ables of the
whe at used in the dail y mix,
x : lb of
y mix.
y : lb of soyabean use d in the dail
to opt imi ze
2. Objective Function we wish
to min imiz e the tota l daily cos
t (in l') of the feed mix that is
The objective function will be
Min imiz e Z = 0.2 t + 0.2y.

mu st satisfy
3. Constraints that the solution ents .
diet ary requ irem
daily amo unt of mix and the
The constra ints repr esen t the
700 lb of feed eac h day
The catt le farm requires atle ast
x +y ~ 700 .

y lb of soy bea n is (0.09x+0.6 y


)lb.
incl ude d in x lb of whe at and
The amo unt of carb ohy drat es
(x + y)lb. that is,
leas! 30% of the tota l feed mix
This qua ntity sho uld equ al at
(0.09x + 0.6 y) ~ 0 .3(x + y ).
y lb of soy bea n is
r incl ude d in x lb of whe al and
Sim ilar ly, the amo unt of fibe
(0.0 2t + 0.06y)lb.
y)lb. that is,
5% of the tota l feed mix (x +
Thi s qua ntit y sho uld be atrn ost
(0.0 2x + 0.0 6y) ~ 0.0 5(x +
y).
fy the non -neg ativity
as x and y repr esen t the lb of whe at hence x and y sati
In additio n,
constra ints that is,
x,y ~ 0.

RAT ION S RESEAR CH fN PYT HON


50 CHA PTE R 3. S11JDY OF OPE
S. Y.B.Sc.(Computer Science)
Python Programming Language II

Hence, the above problem can be formulated as follows:

Minimize Z = 0.2x + 0.8y,


subject to,

o.21x - o.3y ~o
0.03x - 0.0ly ~0
X, y :2:0.

The Python Library PuLP provides methods to solve such kind of problems. Refer the
following code to solve such a problem us ing this library.

import pulp asp


Lp_prob = p.LpProblem('Problem', p.LpKinimize)
x = p . LpVariable("x", lowBound = 6))
y = p.LpVariable("y", lowBound = 61)
# Objective Function
Lp_prob += 8.2 * x + 8 . 8 * y
Lp_prob += x + y >= 788
Lp_prob += 8.21*x -8.38*y <= 8
Lp_prob += 8.83*x -8.81*y >= 8
print(Lp_prob)

The above code will display the L.P.P. ln order to solve the L .P.P. we wiU use the Lp_prob. solve()
function defined in PuLP.

status= Lp_prob.solve()
print(p.LpStatus[status])
print(p.value(x), p.value(y),p . value(Lp_prob.objective))

This gives the value of x =411. 76471, y =288.23529 and the minimum value of
Z = 312.94117400000005.

SI CHAPTER 3. STUDY OF OPERATIONS RESEARCH IN PYTHON


S.Y.B.Sc.(Computer Science) Python Programming Language n

3.2 Introduction to Simplex Method in Python


Simplex method or simplex algorithm is one of the very popular ways of solving a Linear
Programming problem. The approach is to solve the problem using slack variables, tableau
and pivot variables as a means to finding out the optimal solution to a LPP problem.
The Simplex algorithm operates oo linear program in Canonical form given by,
Maximize cTx, subject to Ax :s; band x 2: 0, where,

• c = (c,, c2, .... , c,.) are the coeffecients in the objective function.
• x = (x 1, x2, ... , x,.) are the variables of the problem.
• A is a m x II matrix of coeffecieots
• b = (b 1, b2, ..., bm) is a vector of non-negative constants.

Problem 2: Consider a production house producing 4 items. Note that the daily items
produced produced for the four items are given by x , y, z, w respectively. The goal is to dally
production so as to yield maximum profit considering the following constraints;

• The profit per unit of the item is t20, t 12. t40 and '25, respectively.
• The total number of items produced per day cannot exceed 50.
• The items require the consumption of two types of raw material namely A and B and
their consumption per unit of item which is given in the table below;
Raw Material item 1 item 2 item3 item4
A 3 2 1 0
B 0 1 2 3
• Due to costing with the logistics the production house can consume up to 100 units of
raw material A and 90 units of raw material B.

Determine the quantities x, y, z. w so as to maximize the profit.


Problem Formulation : The above problem can be formulated as follows:
Maximize Z = 20x + 12y + 40z + 25w, subject to the constraints,

x+y+z+w ;s; 50
3x + 2y + z ;s; 100
y +2z +3w :s: 90
x, y, z, w 2: 0.

52 CHAPTER 3. STlJDY OF OPERATIONS RESEARCH IN PYTIION


S. Y.8 .Sc.(Computer Science) Python Programming Language JI

To solve this problem using a simplex method, we will use the linprog () function defined
in the scipy.optimize module. Note the function linprog() solves only minimization
problems. Incase of problem of Maximization type,convert the problem in to minimization
type as shown below;

• Replace the objective function Max z = x + y by Min -z = -x - y.


• Convert the inequalities of•~ • type to ' 5' type by multiplying by -1.

Also note that while solving the problem using Jinprog functions three methods are avaliable.

(a) method="interior point" which selects the interior point method.This is set as a default
option.
(b) method="revised simplex" which selects the revised twp phase simplex method.
(c) method="simplex" selects the primitive simplex method.

Refer the code below to solve the above problem;

from scipy.optimize import linprog


objfn=[-29, -12, -49, -25]
lbs= [[l, 1, 1, l].
[3, 2, 1, 8],
[&, 1, 2, 3]]
rhs=[ 58, 188,98]
opt= linprog(c--0bjfn, A_ub=lhs, b_ub=rhs,
method="revised simplex")
opt

The above code returns the following output,

con: array([], dtype=float64)


fun: - 1988.8
message: 'Optimization terminated successfully.'
nit: 2
slack: array([ 8., 48 . , &.])
status: 8
success: True
x: array([ 5. , 8 . , 45 ., 8 . ])

53 CHAPTER J . STUDY OF OPERATIONS RESEARCH IN PYTHON


S. Y.8 .Sc.(Computer Science) Python Programming Language n

Hence, the values of the quantities are x = 5, y = 0, z = 45, w = 0 and the maximum profit
obtained in such a case is 1900.
In addition, these are some other conclusions that one can draw;
• The third item brings the largest profit per unit so that the production house will produce
it on a large scale.
• The first slack variable is O which means that the first constraint mentioned turns out
to be an equality. It means that the production house produces 50 units of all the items
per day which is to its full capcity.
• The second slack variable is 40 which means that the production house consumes 60
units of the raw material A out of the avaliable 100 units.
• The third slack variable is Owhich means that the production house consumes all of
the 90 units of the raw material B. The entire raw material is consumed for the third
item because of which the second and fourth item cannot be manufactured as well as
the third item cannot be manufactured by a quantity more than 45. There is a deficit of
the raw material B.

3.3 Self Exercises


l. Solve the L.P.P. problem given by
Maximize Z = 4x + y
subject to the constraints
x + y ;::; 50, 3x + y ;::; 90 and x, y 2:: 0

2. Solve the L.P.P. problem given by


Maximiz.e Z = 4x + y
subject to the constraints
x + 3y;::; 60, x + y 2:: 10, x ;::; y and x , y 2:: 0
3. Solve the L.P.P. problem given by
Minimize Z = -50x + 20y
subject to the constraints
2x - y 2:: -5, 3x + y 2:: 3, 2x - 3y ;::; 12 and x, y 2:: 0
4 . A manufacturer bas three machines I, II and m installed in bis factory. Machines I and II
are capable of being operated forat most 12 hours whereas machine m must be operated for

54 CHAPTER 3. STUDY OF OPERATIONS RESEARCH IN PYTHON


S. Y.B.Sc .(Comp uter Science ) Python Program ming Langua ge n

ng the use of all the


atleast 5 hours a day. She produc es only two items M and N each requiri
of each of M and N on
three machin es.The numbe r of hours require d for produc ing I unit
the three machi nes are given in the folJowing table:

I II m
M I 2 1
N 2 l 1.25

How many of each


She makes a profit of f600 and f 400 on items M and N respectively.
she can seU all the items
item s hould she produc e so as to maxim ise her profit assum ing that
and solve the Linear
that she produc ed? What will be the maxim um profit? Fonnu late
Progra mming Prob]e m.
From these locatio ns,
5. There are two factories located one at place P and the other at place Q.
a certain comm odity is to be delive red to each of the three
depots situate d at A, B and C.
4 units of the commo dity
The weekly require ments of the depots are respectively. 5, 5 and
tively 8 and 6 units. The
while the produc tion capaci ty of the factori es at P and Q are respec
cost of transp ortatio n per unit is given below:

A B C
p 160 100 150
Q 100 120 100

depot in order that the


How many units should be transp orted from each factory to each
ortation cost?
transp ortatio n cost is minim um. What will be the minim um transp

6. Solve the following proble m using Simple x metho d:

Maxim ize Z = 2x1 - x2 + 2x3

subjec t to,
2x1 + xi$ 10
x, + 2x2 - 2x3 5 20
x2 + 2x3 5 5
x1,x2 ,x3 ~ 0

CHAPTER 3. STUDY OF OPERATI0:'11S RESEARCH IN PYTHON


55
Python Programming Lan gua
ge n
S. Y.B .Sc.(C om puter Sci enc e)
spa per adver-
rna tive s for a com pan y inc Jude teJevision, rad io. and new
7. Th e adverti sin g alte giv en in tab le;
me nts . Th e cos ts and esl ima tes for aud ien ce cov era ge are
1.ise
20 00 600 300
Co st per add in f
1,00.000 400 00 18000
Au die nce per add
a sin gle com pan y
per lim its the num ber of we ekl y adv ert ise me nts fro m
Th e locaJ newspa me dia , no
er to bal anc e the adv ert isin g am ong the thr ee typ es of
to ten . Moreover, in ord the rad io, and at Jcast
tota l num ber of adv ert ise me nts sho uld occ ur on
more than hal f of the ,200. Ho w ma ny
tele vis ion . Th e week.Jy adv ert isin g bud get is f18
10% sho uld occ ur on the totaJ
run in eac h of the thr ee typ es of me dia to ma xim ize
advertisements sho uld be x me tho d.
ble m and sol ve usi ng sim ple
aud ience? For mu late the pro
DOD

56 RATIONS RESEAR CH IN PY nlO N


CHAPTER 3. STUDY OF OPE

You might also like