01 02 04 NITK Python Tutorial

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

0_Contents file:///C:/Users/Shyam/AppData/Local/Temp/0_Contents.

html

Tutorial on Python Programming

Outline

1. Numpy Library

2. Basics of python

3. Functions

4. Control Statement

5. Materics

6. Ploting

7. Scipy Library
In [ ]:

1 of 1 27-10-2020, 08:32
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

TUTORIAL for Python Programming

Introduction of NumPy
NumPy is a Python package. It stands for 'Numerical Python'. It is a library consisting of multidimensional
array objects and a collection of routines for processing of array.

Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package Numarray was also
developed, having some additional functionalities.
In 2005, Travis Oliphant created NumPy package by incorporating the features of Numarray into Numeric
package. There are many contributors to this open source project.

Documentation for NumPy


https://numpy.org/doc/ (https://numpy.org/doc/)

Operations using NumPy


Using NumPy, a developer can perform the following operations −

Mathematical and logical operations on arrays.


Fourier transforms and routines for shape manipulation.
Operations related to linear algebra. NumPy has in-built functions for linear algebra and random
number generation.

NumPy – A Replacement for MatLab


NumPy is often used along with packages like SciPy (Scientific Python) and Mat−plotlib (plotting library).
This combination is widely used as a replacement for MatLab, a popular platform for technical computing.
However, Python alternative to MatLab is now seen as a more modern and complete programming
language.

It is open source, which is an added advantage of NumPy.

1 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

The Basics
NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually
numbers), all of the same type, indexed by a tuple of positive integers.
In NumPy dimensions are called axes. The number of axes is rank.

For example, the coordinates of a point in 3D space [1, 2, 1] is an array of rank 1, because it has one
axis. That axis has a length of 3.
In the example given below, the array has rank 2 (it is 2-dimensional). The first dimension (axis) has a
length of 2, the second dimension has a length of 3.

[[ 1., 0., 0.], [ 0., 1., 2.]]

NumPy’s array class is called ndarray. It is also known by the alias array. Note that numpy.array is not the
same as the Standard Python Library class array.array, which only handles one-dimensional arrays and
offers less functionality.
The more important attributes of an ndarray object are:

1. ndarray.ndim:
The number of axes (dimensions) of the array. In the Python world, the number of dimensions is
referred to as rank.
2. ndarray.shape:
The dimensions of the array. This is a tuple of integers indicating the size of the array in each
dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape
tuple is therefore the rank, or number of dimensions, ndim.
3. ndarray.size:
The total number of elements of the array. This is equal to the product of the elements of shape.
4. ndarray.dtype: An object describing the type of the elements in the array. One can create or specify
dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32,
numpy.int16, and numpy.float64 are some examples.

Python list ( [ ] )
1. A list is a collection of data elements arranged sequentially.

2. They are mutable in nature, and data can inserted, removed and appended.
3. Lists are enclosed by a pair of squared brackets '[]'

4. Lists in Python are heterogeneous. A list can contain any different type of data.

5. Lists are especially good for keeping track of things that change in the course of the program
execution.

6. A list could be created by a pair of squared-brackets [] or list()..

2 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

Python tuples ( ( ) )
Similar to lists, tuples are sequences of arbitrary items.

1. Tuples are the immutable collection sequence types in Python.

2. Tuples can't be modified using add, delete, or changing of items once the tuple is created. A tuple is
thus a constant list type.
3. A tuple can be created using a pair of parenthesis ().

4. Notice that it is different from how a list can be created by saying "list()"

Function numpy.arange()
1. It is one of the array creation routines based on numerical ranges

2. It creates an instance of ndarray with evenly spaced values and returns the reference to it.

3. You can define the interval of the values contained in an array, space between them, and their type
with four parameters of arange():
numpy.arange(start, stop, step, dtype=None)

Illustrative Examples
In [26]: import numpy as np
a = np.arange(4)
a

Out[26]: array([0, 1, 2, 3])

In [86]: a = np.arange(3.0) ##
a

Out[86]: array([0., 1., 2.])

In [7]: import numpy as np


a = np.arange(2,8,1) ##
a

Out[7]: array([2, 3, 4, 5, 6, 7])

In [39]: import numpy as np


a = np.arange(3,9,3) ##
a

Out[39]: array([3, 6])

3 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

Alternate method for Array Creation


There are several ways to create arrays.

For example, you can create an array from a regular Python list or tuple using the array function. The type
of the resulting array is deduced from the type of the elements in the sequences.

A frequent error consists in calling array with multiple numeric arguments, rather than providing a
single list of numbers as an argument.

WRONG

RIGHT

Array transforms sequences of sequences into two-dimensional arrays, sequences of sequences


of sequences into three-dimensional arrays, and so on.

In [17]: import numpy as np


a = np.array([2,3,4,6])
a

Out[17]: array([2, 3, 4, 6])

Printing Arrays
When you print an array, NumPy displays it in a similar way to nested lists, but with the following layout:

The last axis is printed from left to right


The second-to-last is printed from top to bottom
The rest are also printed from top to bottom, with each slice separated from the next by an empty
line.

One-dimensional arrays are then printed as rows, bidimensionals as matrices and tridimensionals
as lists of matrices.

In [21]: import numpy as np


a = np.array([2,3,4,6])
print(a)

[2 3 4 6]

In [22]: X2D = np.array([[11 ,12,13,11], [21, 22, 23, 24], [31,32,33,34]])


print('2D Numpy Array')
print(X2D)

2D Numpy Array
[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]

4 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

IIlustarive Examples of ndarray.shape[]


In [43]: # Example 1
#Get Dimensions of a 1D NumPy array using ndarray.shape
# Create a Numpy array from list of numbers
X1D = np.array([4, 5, 6, 7, 8, 9, 10, 11])

#Get number of elements of this 1D NumPy array i.e.


print('Shape of 1D numpy array : ', X1D.shape)
print('length of 1D numpy array : ', X1D.shape[0])
# np.size(X1D, axis=None) #Total Number of elements in NumP
y array
print(len(X1D))

In [46]: #Example 2
# Create a 2D Numpy array list of list
import numpy as np
X2D = np.array([[11 ,12,13,11], [21, 22, 23, 24], [31,32,33,34]])
print('2D Numpy Array')
print(X2D)
print("Shape of 2D Array")
print(X2D.shape)

2D Numpy Array
[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
Shape of 2D Array
(3, 4)

In [21]: #Get number of rows in this 2D NumPy array i.e.


numOfRows = X2D.shape[0]
print('Number of Rows : ', numOfRows)

Number of Rows : 3

In [20]: #Get number of rows in this 2D NumPy array i.e.


numOfRows = np.size(X2D,0)
print('Number of Rows : ', numOfRows)

Number of Rows : 3

In [17]: #Get number of columns in this 2D NumPy array i.e.


numOfColumns = X2D.shape[1]
print('Number of Columns : ', numOfColumns)

Number of Columns : 4

In [18]: # get number of columns in 2D NumPy array


numOfColumns = np.size(X2D, 1)
print('Number of Columns : ', numOfColumns)

Number of Columns : 4

5 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

In [22]: #Get total number of elements in this 2D NumPy array,


totalNumberofElements = X2D.shape[0] * X2D.shape[1]
print('Total Number of elements in 2D Numpy array : ',totalNumberofE
lements )

Total Number of elements in 2D Numpy array : 12

In [23]: #Get total number of elements in this 2D NumPy array:


print('Total Number of elements in 2D Numpy array : ', np.size(X2D))

Total Number of elements in 2D Numpy array : 12

Complete example
In [52]: import numpy as np
a1 = np.arange(15) ##
print ("a1 = ",a1)
dim1=a1.ndim
shape1=a1.shape
size1=a1.itemsize
datatype1=a1.dtype.name
print ("Number of axes (dimensions) of the array = ", dim1)
print ("Dimension of the array = ", shape1)
print ("Total number of elements of the array = ", size1)
print ("Type of the elements in the array = ", datatype1)

a1 = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
Number of axes (dimensions) of the array = 1
Dimension of the array = (15,)
Total number of elements of the array = 4
Type of the elements in the array = int32

Function reshape()
Using the reshape() function, we can specify the row x column shape that we are seeking.

The Convolution2D layers in Keras however, are designed to work with 3 dimensions per example.
They have 4-dimensional inputs and outputs. This covers colour images (nb_samples,
nb_channels, width, height), but more importantly, it covers deeper layers of the network, where
each example has become a set of feature maps i.e. (nb_samples, nb_features, width, height).

For example :
mnist.load_data() supplies the MNIST digits with structure (nb_samples, 28, 28) i.e. with 2 dimensions per
example representing a greyscale image 28x28.

6 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

Illustrative Examples of 2D array using


reshape()
In [32]: a = np.arange(12) # 1D array
print(a)
print("Shape of 1D Array")
print(a.shape)

[ 0 1 2 3 4 5 6 7 8 9 10 11]
Shape of 1D Array
(12,)

In [33]: ## reshape- it genearte matrix of 2 rows and 3 columns


c = a.reshape(2,6) # 2D array
print(c)
print("Shape of 2D Array")
print(c.shape)

[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]
Shape of 2D Array
(2, 6)

In [34]: ## reshape- it genearte matrix of 2 rows and 3 columns


c = a.reshape(6,2) # 2D array
print(c)
print("Shape of 2D Array")
print(c.shape)

[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]]
Shape of 2D Array
(6, 2)

In [35]: ## reshape- it genearte matrix of 2 rows and 3 columns


c = a.reshape(4,3) # 2D array
print(c)
print("Shape of 2D Array")
print(c.shape)

[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
Shape of 2D Array
(4, 3)

7 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

In [36]: ## reshape- it genearte matrix of 2 rows and 3 columns


c = a.reshape(3,4) # 2D array
print(c)
print("Shape of 2D Array")
print(c.shape)

[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Shape of 2D Array
(3, 4)

In [37]: ## reshape- it genearte matrix of 2 rows and 3 columns


c = a.reshape(12,1) # 2D array
print(c)
print("Shape of 2D Array")
print(c.shape)

[[ 0]
[ 1]
[ 2]
[ 3]
[ 4]
[ 5]
[ 6]
[ 7]
[ 8]
[ 9]
[10]
[11]]
Shape of 2D Array
(12, 1)

Notice how all of the shapes have to account for the number of elements in the tensor. In our example this
is:
rows * columns = 12 elements

We can use the intuitive words rows and columns when we are dealing with a rank 2 tensor. The
underlying logic is the same for higher dimensional tenors even though we may not be able to use the
intuition of rows and columns in higher dimensional spaces.

Illustrative Examples of 3D Array using


reshape()

8 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

In [27]: #Example 1:
## reshape- it genearte 3D matrix
c = np.arange(24).reshape(2,3,4) # 3D array
print(c)

print('Axis 0 size : ', np.size(c, 0))


print('Axis 1 size : ', np.size(c, 1))
print('Axis 2 size : ', np.size(c, 2))
print("Shape of 3D Array")
print(c.shape)

[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]

[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
Axis 0 size : 2
Axis 1 size : 3
Axis 2 size : 4
(2, 3, 4)

In [28]: # Example 2:

c = np.arange(27).reshape(3,3,3) # 3D array
print(c)

#Get number of elements per axis in 3D numpy array i.e.


print('Axis 0 size : ', np.size(c, 0))
print('Axis 1 size : ', np.size(c, 1))
print('Axis 2 size : ', np.size(c, 2))
print("Shape of 3D Array")
print(c.shape)

[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]

[[ 9 10 11]
[12 13 14]
[15 16 17]]

[[18 19 20]
[21 22 23]
[24 25 26]]]
Axis 0 size : 3
Axis 1 size : 3
Axis 2 size : 3
Shape of 3D Array
(3, 3, 3)

9 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

In [24]: # Example 3:
# reshape function
a = np.arange(15).reshape(3, 5) ## reshape- it genearte matrix
of 3 rows and 5 column
print ("a = ",a)
dim=a.ndim
shape=a.shape
size=a.itemsize
datatype=a.dtype.name
print ("Number of axes (dimensions) of the array = ", dim)
print ("Dimension of the array = ", shape)
print ("Total number of elements of the array = ", size)
print ("Type of the elements in the array = ", datatype)

a = [[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Number of axes (dimensions) of the array = 2
Dimension of the array = (3, 5)
Total number of elements of the array = 4
Type of the elements in the array = int32

Illustrative Examples of 4D Array using


reshape()

10 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

In [25]: # Example 4:
## reshape- it genearte matrix of 2 rows and 3 columns
c1 = np.arange(12).reshape(3,4) # 2D array
print(c1)
c = c1.reshape(3,2,2,1) # 4D array
print("Array after reshaping")
print(c)
print("Shape of Array after reshaping")
print(c.shape)

[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Array after reshaping
[[[[ 0]
[ 1]]

[[ 2]
[ 3]]]

[[[ 4]
[ 5]]

[[ 6]
[ 7]]]

[[[ 8]
[ 9]]

[[10]
[11]]]]
Shape of Array after reshaping
(3, 2, 2, 1)

Can We Reshape Into any Shape?


Yes, as long as the elements required for reshaping are equal in both shapes.

We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array but we cannot reshape it into
a 3 elements 3 rows 2D array as that would require 3x3 = 9 elements.

If an array is too large to be printed, NumPy


automatically skips the central part of the array and
only prints the corners:
In [29]: print(np.arange(10000))

[ 0 1 2 ... 9997 9998 9999]

11 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

In [37]: print(np.arange(10000).reshape(100,100))

[[ 0 1 2 ... 97 98 99]
[ 100 101 102 ... 197 198 199]
[ 200 201 202 ... 297 298 299]
...
[9700 9701 9702 ... 9797 9798 9799]
[9800 9801 9802 ... 9897 9898 9899]
[9900 9901 9902 ... 9997 9998 9999]]

To disable this behaviour and force NumPy to print the entire array, you can change the printing options using
set_printoptions. np.set_printoptions(threshold='nan')

ndarry.itemsize
This array attribute returns the length of each element of array in bytes

Length of one array element in bytes.

Illustraive examples using ndarry.itemsize


In [30]: #Example 1
# dtype of array is int8 (1 byte)
import numpy as np
x = np.array([2,4,6,8,10], dtype = np.int8)
print(x)
print(x.itemsize)

[ 2 4 6 8 10]
1

In [31]: #Example 2
# dtype of array is int16 (2 bytes)
import numpy as np
x = np.array([2,4,6,8,10], dtype = np.int16)
print(x)
print(x.itemsize)

[ 2 4 6 8 10]
2

In [32]: #Example 3
# dtype of array is int32 (4 bytes)
import numpy as np
x = np.array([2,4,6,8,10], dtype = np.int32)
print(x)
print(x.itemsize)

[ 2 4 6 8 10]
4

12 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

In [33]: #Example 4
# dtype of array is float32 (4 bytes)
import numpy as np
x = np.array([2,4,6,8,10], dtype = np.float32)
print(x)
print(x.itemsize)

[ 2. 4. 6. 8. 10.]
4

In [34]: #Example 5
# dtype of array is float32 (8 bytes)
import numpy as np
x = np.array([2,4,6,8,10], dtype = np.float64)
print(x)
print(x.itemsize)

[ 2. 4. 6. 8. 10.]
8

In [37]: #Example 6
# dtype of array is complex64 (8 bytes)
import numpy as np
x = np.array([2,4,6,8,10], dtype = np.complex128)
print(x)
print(x.itemsize)

[ 2.+0.j 4.+0.j 6.+0.j 8.+0.j 10.+0.j]


16

Get Dimensions of a 3D numpy array using


numpy.size()
In [54]: # Create a 3D Numpy array list of list of list
X3D = np.array([ [[11, 12, 13, 11], [21, 22, 23, 24], [31, 32, 33, 3
4]],
[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]] ])
print(X3D)

#Get number of elements per axis in 3D numpy array i.e.

print('Axis 0 size : ', np.size(X3D, 0))


print('Axis 1 size : ', np.size(X3D, 1))
print('Axis 2 size : ', np.size(X3D, 2))

[[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]

[[ 1 1 1 1]
[ 2 2 2 2]
[ 3 3 3 3]]]
Axis 0 size : 2
Axis 1 size : 3
Axis 2 size : 4

13 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

Illustrative examples of Other Array Creation


In [6]: import numpy as np
#b = np.array(([(1.5,2,3), (4,5,6)]),dtype=int)
b = np.array([(1.5,2,3), (4,5,6)])
b

Out[6]: array([[1.5, 2. , 3. ],
[4. , 5. , 6. ]])

The type of the array can also be explicitly specified at creation time:

In [7]: c = np.array( [ [1,2], [3,4] ], dtype=complex )


c

Out[7]: array([[1.+0.j, 2.+0.j],


[3.+0.j, 4.+0.j]])

To create sequences of numbers, NumPy provides a function analogous to range that returns arrays
instead of lists.

In [8]: np.arange( 0, 2, 0.3 ) # it accepts float arguments

Out[8]: array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])

When arange is used with floating point arguments, it is generally not possible to predict the number of
elements obtained, due to the finite floating point precision. For this reason, it is usually better to use the
function linspace that receives as an argument the number of elements that we want, instead of the step:

In [9]: from numpy import pi


np.linspace( 0, 2, 9 ) # 9 numbers from 0 to 2

Out[9]: array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])

14 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

In [12]: # x = np.linspace( 0, 2*pi, 100 ) # useful to evaluate functi


on at lots of points
x = np.linspace( 0, 2*np.pi, 100 ) # useful to evaluate funct
ion at lots of points
f = np.sin(x)
print(x)
print(f)

[0. 0.06346652 0.12693304 0.19039955 0.25386607 0.31733259


0.38079911 0.44426563 0.50773215 0.57119866 0.63466518 0.6981317
0.76159822 0.82506474 0.88853126 0.95199777 1.01546429 1.07893081
1.14239733 1.20586385 1.26933037 1.33279688 1.3962634 1.45972992
1.52319644 1.58666296 1.65012947 1.71359599 1.77706251 1.84052903
1.90399555 1.96746207 2.03092858 2.0943951 2.15786162 2.22132814
2.28479466 2.34826118 2.41172769 2.47519421 2.53866073 2.60212725
2.66559377 2.72906028 2.7925268 2.85599332 2.91945984 2.98292636
3.04639288 3.10985939 3.17332591 3.23679243 3.30025895 3.36372547
3.42719199 3.4906585 3.55412502 3.61759154 3.68105806 3.74452458
3.8079911 3.87145761 3.93492413 3.99839065 4.06185717 4.12532369
4.1887902 4.25225672 4.31572324 4.37918976 4.44265628 4.5061228
4.56958931 4.63305583 4.69652235 4.75998887 4.82345539 4.88692191
4.95038842 5.01385494 5.07732146 5.14078798 5.2042545 5.26772102
5.33118753 5.39465405 5.45812057 5.52158709 5.58505361 5.64852012
5.71198664 5.77545316 5.83891968 5.9023862 5.96585272 6.02931923
6.09278575 6.15625227 6.21971879 6.28318531]
[ 0.00000000e+00 6.34239197e-02 1.26592454e-01 1.89251244e-01
2.51147987e-01 3.12033446e-01 3.71662456e-01 4.29794912e-01
4.86196736e-01 5.40640817e-01 5.92907929e-01 6.42787610e-01
6.90079011e-01 7.34591709e-01 7.76146464e-01 8.14575952e-01
8.49725430e-01 8.81453363e-01 9.09631995e-01 9.34147860e-01
9.54902241e-01 9.71811568e-01 9.84807753e-01 9.93838464e-01
9.98867339e-01 9.99874128e-01 9.96854776e-01 9.89821442e-01
9.78802446e-01 9.63842159e-01 9.45000819e-01 9.22354294e-01
8.95993774e-01 8.66025404e-01 8.32569855e-01 7.95761841e-01
7.55749574e-01 7.12694171e-01 6.66769001e-01 6.18158986e-01
5.67059864e-01 5.13677392e-01 4.58226522e-01 4.00930535e-01
3.42020143e-01 2.81732557e-01 2.20310533e-01 1.58001396e-01
9.50560433e-02 3.17279335e-02 -3.17279335e-02 -9.50560433e-02
-1.58001396e-01 -2.20310533e-01 -2.81732557e-01 -3.42020143e-01
-4.00930535e-01 -4.58226522e-01 -5.13677392e-01 -5.67059864e-01
-6.18158986e-01 -6.66769001e-01 -7.12694171e-01 -7.55749574e-01
-7.95761841e-01 -8.32569855e-01 -8.66025404e-01 -8.95993774e-01
-9.22354294e-01 -9.45000819e-01 -9.63842159e-01 -9.78802446e-01
-9.89821442e-01 -9.96854776e-01 -9.99874128e-01 -9.98867339e-01
-9.93838464e-01 -9.84807753e-01 -9.71811568e-01 -9.54902241e-01
-9.34147860e-01 -9.09631995e-01 -8.81453363e-01 -8.49725430e-01
-8.14575952e-01 -7.76146464e-01 -7.34591709e-01 -6.90079011e-01
-6.42787610e-01 -5.92907929e-01 -5.40640817e-01 -4.86196736e-01
-4.29794912e-01 -3.71662456e-01 -3.12033446e-01 -2.51147987e-01
-1.89251244e-01 -1.26592454e-01 -6.34239197e-02 -2.44929360e-16]

15 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

Stacking together different arrays


Several arrays can be stacked together along different axes:
np.vstack: We can combine two arrays in row-wise (axis-0)

np.hstack: We can combine two arrays in column-wise (axis-1

Concatenating tensors in deep learning


We combine tensors using the cat() function, and the resulting tensor will have a shape that depends on
the shape of the two input tensors.
We can combine t1 and t2 row-wise (axis-0) in the following way:

We can combine them column-wise (axis-1) like this:

In [62]: a =np.array([[ 0, 1],


[2,3]])
b=np.array([[ 4, 5],
[6,7]])
print('a=',a)
print('b=',b)

a= [[0 1]
[2 3]]
b= [[4 5]
[6 7]]

In [63]: np.vstack((a,b))

Out[63]: array([[0, 1],


[2, 3],
[4, 5],
[6, 7]])

In [64]: np.hstack((a,b))

Out[64]: array([[0, 1, 4, 5],


[2, 3, 6, 7]])

Splitting one array into several smaller ones


Using hsplit, you can split an array along its horizontal axis, either by specifying the number of equally
shaped arrays to return, or by specifying the columns after which the division should occur. vsplit splits
along the vertical axis, and array_split allows one to specify along which axis to split.

16 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html

In [16]: import numpy as np


b = np.arange(24).reshape(2,12)
b

Out[16]: array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],


[12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])

In [14]: np.hsplit(b,3) # Split a into 3 array of dimention 2 x 4

Out[14]: [array([[ 0, 1, 2, 3],


[12, 13, 14, 15]]),
array([[ 4, 5, 6, 7],
[16, 17, 18, 19]]),
array([[ 8, 9, 10, 11],
[20, 21, 22, 23]])]

In [17]: np.hsplit(b,(3,4)) # Split a after the third and the fourth column

Out[17]: [array([[ 0, 1, 2],


[12, 13, 14]]),
array([[ 3],
[15]]),
array([[ 4, 5, 6, 7, 8, 9, 10, 11],
[16, 17, 18, 19, 20, 21, 22, 23]])]

In [ ]:

17 of 17 29-10-2020, 12:58
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

TUTOTIAL for Python Programming

Python Basics
In [1]: # Simple program #(Select shell + ctrl+/) for commenting whole
shell

print ("Hello World"); # displaying the hello world by print

Hello World

Indentation
Python does not use braces({}) to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented
the same amount.

In [3]: if True:
print ("Answer")
print () # Prints a blank line
print ("True")

else:
print ("Answer")
print ("False")

Answer

True

Strings in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the
same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines. For example, all the following are legal

1 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

In [4]: word = 'word'


sentence = "This is a sentence."
paragraph = '''This is a paragraph. It is
made up of multiple lines and sentences.'''

#paragraph = """This is a paragraph. It is


#made up of multiple lines and sentences."""

print (word)
print()
print (sentence)
print()
print (paragraph)

word

This is a sentence.

This is a paragraph. It is
made up of multiple lines and sentences.

Comments in Python
A hash sign (#) that is not inside a string literal is the beginning of a comment. All characters after the #,
up to the end of the physical line, are part of the comment and the Python interpreter ignores them. There
are no multiline comments. One has to comment each line.

In [3]: # First comment


print ("Hello, Python!") # second comment

Hello, Python!

Python variables
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to
variables.

The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable.

In [5]: counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string
#name = 'John' # A string

print (counter)
print (miles)
print (name)

100
1000.0
John

2 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.

In [9]: a = b = c = 1

d, e, f = 1, 2, "john"

print (a,b,c) # printing multiple output


print (d,e,f) #printing multiple output thait is numbers and str
ing

1 1 1
1 2 john

Standard Data Types


Numbers
String
List
Tuple
Dictionary

Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to them.

In [10]: var1 = 1
var2 = 10
print(var1,var2)

1 10

Python supports three different numerical types

int (signed integers)


float (floating point real values)
complex (complex numbers)

3 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

In [11]: var_int = 10
var_float = 10.5
var_complex = 10+5j

print(var_int, type(var_int))
print(var_float, type(var_float))
print(var_complex, type(var_complex))

10 <class 'int'>
10.5 <class 'float'>
(10+5j) <class 'complex'>

Python lists
A list contains items separated by commas and enclosed within square brackets ([]).

The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0
in the beginning of the list and working their way to end -1.

The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

In [12]: list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']
zeros=[0, 0, 0, 0]
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists

#list.extend(tinylist)
#print(list)

list.append(zeros)
print(list)

['abcd', 786, 2.23, 'john', 70.2]


abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, [0, 0, 0, 0]]

4 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

Python Tuples
A tuple is another sequence data type that is similar to the list.

A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed
within parenthesis.

The main difference between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements
and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples
can be thought of as read-only lists.

In [2]: tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print (tuple) # Prints complete tuple


print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple

('abcd', 786, 2.23, 'john', 70.2)


abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

In [1]: # tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


# list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
# tuple[2] = 1000 # Invalid syntax with tuple , will show error
# list[2] = 1000 # Valid syntax with list

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed.
Similar case is possible with lists

Python Dictionary
Python's dictionaries are kind of hash-table type. A dictionary key can be almost any Python type, but are
usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([ ]).

Dictionaries have no concept of order among the elements.

5 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

In [36]: dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one']) # Prints value for 'one' key


print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values

This is one
This is two
{'name': 'john', 'code': 6734, 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['john', 6734, 'sales'])

Datatype conversion
int(x [,base]) : Converts x to an integer. The base specifies the base if x is a string.

In [13]: string1 = "111"


string2 = "1111"
float1 = 2.5

num = int (string1) ##default base is 10


num1 = int(string1,8 ) #1x8^2+1x8^1+1x8^0=72
num2 = int(string2,2) ##1x2^3+1x2^2+1x2^1+1x2^0
num3 = int (float1)
print(num)
print(num1)
print(num2)
print(num3)
print(type (string1))
print(type (float1))
print(type (num1))
print(type (num2))
print(type (num3))

111
73
15
2
<class 'str'>
<class 'float'>
<class 'int'>
<class 'int'>
<class 'int'>

In [ ]:

6 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

Python Operators
Python language supports the following types of operators

Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators

Python Arithmetic Operators


Assume variable a holds the value 10 and variable b holds the value 21

Operator Description Example

Assigns values from right side


= c = a + b assigns value of a + b into c
operands to left side operand

It adds right operand to the left


+= Add AND operand and assign the result to left c += a is equivalent to c = c + a
operand

It subtracts right operand from the left


-= Subtract AND operand and assign the result to left c -= a is equivalent to c = c - a
operand

It multiplies right operand with the left


Multiply AND operand and assign the result to left c a is equivalent to c = c a
operand

It divides left operand with the right


/= Divide AND operand and assign the result to left c /= a is equivalent to c = c / a
operand

It takes modulus using two operands


%= Modulus AND c %= a is equivalent to c = c % a
and assign the result to left operand

Performs exponential (power)


Exponent AND calculation on operators and assign c a is equivalent to c = c a
value to the left operand

It performs floor division on operators


//= Floor Division c //= a is equivalent to c = c // a
and assign value to the left operand

7 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

Python Bitwise Operators


Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; Now in
binary format they will be as follows

a = 0011 1100

b = 0000 1101

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

Python's built-in function bin() can be used to obtain binary representation of an integer number.

Operator Description Example

Operator copies a bit, to the result, if it


& Binary AND (a & b) (means 0000 1100)
exists in both operands

It copies a bit, if it exists in either


| Binary OR (a | b) = 61 (means 0011 1101)
operand.

It copies the bit, if it is set in one


^ Binary XOR (a ^ b) = 49 (means 0011 0001)
operand but not both.

(~a ) = -61 (means 1100 0011 in 2's


It is unary and has the effect of
~ Binary Ones Complement complement form due to a signed
'flipping' bits.
binary number.

The left operand's value is moved left


<< Binary Left Shift by the number of bits specified by the a << = 240 (means 1111 0000)
right operand.

The left operand's value is moved right


>> Binary Right Shift by the number of bits specified by the a >> = 15 (means 0000 1111)
right operand.

Python Logical Operators


The following logical operators are supported by Python language. Assume variable a holds True and
variable b holds False

Operator Description Example

If both the operands are true then


and Logical AND (a and b) is False.
condition becomes true.

If any of the two operands are non-


or Logical OR (a or b) is True.
zero then condition becomes true.

Used to reverse the logical state of its


not Logical NOT Not(a and b) is True.
operand.

8 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There
are two membership operators

Operator Description Example

Evaluates to true if it finds a variable in


x in y, here in results in a 1 if x is a
in the specified sequence and false
member of sequence y.
otherwise.

Evaluates to true if it does not finds a


x not in y, here not in results in a 1 if x
not in variable in the specified sequence and
is not a member of sequence y.
false otherwise.

Python Identity Operators


Identity operators compare the memory locations of two objects. There are two Identity operators

Operator Description Example

Evaluates to true if the variables on


x is y, here is results in 1 if id(x) equals
is either side of the operator point to the
id(y).
same object and false otherwise.

Evaluates to false if the variables on


x is not y, here is not results in 1 if id(x)
is not either side of the operator point to the
is not equal to id(y).
same object and true otherwise.

Python Operators Precedence


S.No. Operator Description

1 Exponentiation (raise to the power)

Ccomplement, unary plus and minus


2 ~+- (method names for the last two are
+@ and -@)

Multiply, divide, modulo and floor


3 * / % //
division

4 +- Addition and subtraction

5 >> << Right and left bitwise shift

6 & Bitwise 'AND'

Bitwise exclusive `OR' and regular


7 ^|
`OR'

8 <= < > >= Comparison operators

9 <> == != Equality operators

10 = %= /= //= -= += *= **= Assignment operators

11 is is not Identity operators

12 in not in Membership operators

13 not or and Logical operators

9 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

Basic Operations
Arithmetic operators on arrays apply elementwise. A new array is created and filled with the result.

In [43]: import numpy as np


a = np.array( [20,30,40,50] )
b = np.arange( 4 )
print(a)
print(b)

[20 30 40 50]
[0 1 2 3]

In [44]: # Addition
c = a+b
c

Out[44]: array([20, 31, 42, 53])

In [45]: # subtraction
c = a-b
c

Out[45]: array([20, 29, 38, 47])

In [4]: # power of 3
b**3

Out[4]: array([ 0, 1, 8, 27], dtype=int32)

In [6]: a<35

Out[6]: array([ True, True, False, False])

In [5]: # sine signal


10*np.sin(a)

Out[5]: array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854])

Unlike in many matrix languages, the product operator * operates elementwise in NumPy arrays. The
matrix product can be performed using the dot function or method:

In [12]: # Array multiplication


A = np.array( [[1,1],
[0,1]] )
B = np.array( [[2,0],
[3,4]] )
A*B # elementwise product

Out[12]: array([[2, 0],


[0, 4]])

10 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

In [13]: #matrix product


A.dot(B) # matrix product

Out[13]: array([[5, 4],


[3, 4]])

In [15]: np.dot(A, B) # another matrix product

Out[15]: array([[5, 4],


[3, 4]])

Some operations, such as += and *=, act in place to modify an existing array rather than create a new one

In [16]: a = np.ones((2,3), dtype=int)


b = np.random.random((2,3))
a *= 3
a

Out[16]: array([[3, 3, 3],


[3, 3, 3]])

In [17]: b += a
b

Out[17]: array([[3.94373083, 3.91265547, 3.99744381],


[3.5436576 , 3.08359143, 3.23677265]])

When operating with arrays of different types, the type of the resulting array corresponds to the more
general or precise one (a behavior known as upcasting).

In [21]: a = np.ones(3, dtype=np.int32)


b = np.linspace(0,np.pi,3)
b.dtype.name

Out[21]: 'float64'

In [22]: c = a+b
c

Out[22]: array([1. , 2.57079633, 4.14159265])

In [23]: c.dtype.name

Out[23]: 'float64'

In [24]: d = np.exp(c*1j)
d

Out[24]: array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j,


-0.54030231-0.84147098j])

Many unary operations, such as computing the sum of all the elements in the array, are implemented as
methods of the ndarray class.

11 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

In [25]: a = np.random.random((2,3))
a

Out[25]: array([[0.73647018, 0.84105766, 0.92700614],


[0.74995884, 0.80766249, 0.89072548]])

In [26]: a.sum()

Out[26]: 4.952880791168187

In [27]: a.min()

Out[27]: 0.7364701794052217

In [28]: a.max()

Out[28]: 0.9270061402955219

By default, these operations apply to the array as though it were a list of numbers, regardless of its shape.
However, by specifying the axis parameter you can apply an operation along the specified axis of an
array:

In [29]: b = np.arange(12).reshape(3,4)
b

Out[29]: array([[ 0, 1, 2, 3],


[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])

In [30]: b.sum(axis=0) # sum of each column

Out[30]: array([12, 15, 18, 21])

In [31]: b.sum(axis=1) # sum of each row

Out[31]: array([ 6, 22, 38])

In [32]: b.min(axis=0) # min of each column

Out[32]: array([0, 1, 2, 3])

In [33]: b.min(axis=1) # min of each row

Out[33]: array([0, 4, 8])

In [35]: b.cumsum(axis=0) # cumulative sum along each


column

Out[35]: array([[ 0, 1, 2, 3],


[ 4, 6, 8, 10],
[12, 15, 18, 21]], dtype=int32)

12 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

In [36]: b.cumsum(axis=1) # cumulative sum along each


row

Out[36]: array([[ 0, 1, 3, 6],


[ 4, 9, 15, 22],
[ 8, 17, 27, 38]], dtype=int32)

Universal Functions
NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called
“universal functions”(ufunc). Within NumPy, these functions operate elementwise on an array, producing
an array as output.

Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers
several functions to create arrays with initial placeholder content. These minimize the necessity of
growing arrays, an expensive operation.

The function zeros creates an array full of zeros, the function ones creates an array full of ones,
and the function empty creates an array whose initial content is random and depends on the state
of the memory. By default, the dtype of the created array is float64.

In [73]: import numpy as np


B = np.arange(3)
B

Out[73]: array([0, 1, 2])

In [38]: np.zeros(5)

Out[38]: array([0., 0., 0., 0., 0.])

In [39]: np.ones(5)

Out[39]: array([1., 1., 1., 1., 1.])

In [72]: np.empty( (2,3))

Out[72]: array([[0., 0., 0.],


[0., 0., 0.]])

In [40]: np.exp(B)

Out[40]: array([1. , 2.71828183, 7.3890561 ])

In [41]: np.sqrt(B)

Out[41]: array([0. , 1. , 1.41421356])

13 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

Indexing Array Elements


One-dimensional arrays can be indexed, sliced and iterated over, much like lists and other Python
sequences.

In [48]: import numpy as np


a = np.arange(10)**3
a

Out[48]: array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729], dtype=in
t32)

In [49]: a[3]

Out[49]: 27

In [51]: a[2:5] # starting from 2nd column to 4th (5-1)colu


mn

Out[51]: array([ 8, 27, 64], dtype=int32)

In [52]: a[:6:2] = -1000 # equivalent to a[0:6:2] = -1000; from start to p


osition 6, exclusive, set every 2nd element to -1000
a

Out[52]: array([-1000, 1, -1000, 27, -1000, 125, 216, 343, 5


12,
729], dtype=int32)

In [53]: a[ : :-1] # reversed a

Out[53]: array([ 729, 512, 343, 216, 125, -1000, 27, -1000,
1,
-1000], dtype=int32)

Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by
commas:

In [54]: b =np.array([[ 0, 1, 2, 3],


[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33],
[40, 41, 42, 43]])
b

Out[54]: array([[ 0, 1, 2, 3],


[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33],
[40, 41, 42, 43]])

In [55]: b[2,3] # [2,3]- 2nd row and 3rd column

Out[55]: 23

14 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html

In [56]: b[0:5, 1] # each row in the second column of b

Out[56]: array([ 1, 11, 21, 31, 41])

In [57]: b[ : ,1] # equivalent to the previous example

Out[57]: array([ 1, 11, 21, 31, 41])

In [65]: b[1,: ] # each column in the second row of b

Out[65]: array([10, 11, 12, 13])

In [63]: b[1:3, : ] # each column in the 2nd and 3nd ro


w of b

Out[63]: array([[10, 11, 12, 13],


[20, 21, 22, 23]])

In [62]: b[0:4,0 ] # first column of each row of b

Out[62]: array([ 0, 10, 20, 30])

In [71]: b[0:4,3 ] # third column of each row of b

Out[71]: array([ 3, 13, 23, 33])

In [39]: x = 3;
y = "Hello"
print( x, y)

z= x
print(id(z))

print(id(x))
print (id(y))

print(x is z)

print(x is y)

3 Hello
94394468535584
94394468535584
140003051108256
True
False

In [ ]:

In [ ]:

15 of 15 29-10-2020, 12:59
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

TUTORIAL for Python Programming

Defining Functions
Defining functions use the def command.
Functions can have arguments and return values
Invoked by the name of the function

Simple Function Definition


In [5]: def happy(): # There is a colon after function definition
print("Happy Birthday to You!") # Function block is indented

Function Call

In [6]: happy()

Happy Birthday to You!

Functions with arguments


In [7]: def square(x):
y = x**2
return y

def hbd(name):
print ("Happy Birthday to ", name)
return

Function calling

In [11]: z = 3;
w = square(z);
print("3x3 = ", w);

print (" 3 squared twice ", square(square(3)))


print (" In expression", 5+square(3))

3x3 = 9
3 squared twice 81
In expression 14

In [5]: def hbd(name):


print ("Happy Birthday to ", name)
return

1 of 3 30-07-2020, 09:16
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

In [13]: # name = shyam


# hbd(name)
name = 'Jon'

hbd(name)

Happy Birthday to Jon

Function Parameters
In [14]: import numpy as np
def addinterest(balance,rate):
balance = balance + np.multiply(balance , rate)
print(balance)
# print(newbalance)
return balance

amount = [100, 200]


rate = 0.05
addinterest(amount, rate)

#print(amount is addinterest)

print("Amount = " , amount );

print(id(addinterest))
id(amount)

[105. 210.]
Amount = [100, 200]
2222603905928

Out[14]: 2222608615368

Arrays
The function can change the value of the arguments

2 of 3 30-07-2020, 09:16
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html

In [63]: def addinterests(bal_list, rate):


# bal_list = bal_list + np.multiply(bal_list , rate)
for i in range (len(bal_list)):
bal_list[i] += (bal_list[i] * rate)

print(id(bal_list))
return

amounts = [1000, 2000, 3000, 5000]


rate = 0.05

addinterests(amounts,rate)

print(amounts)

print(id(amounts))
print(id(addinterests))

140036883512264
[1050.0, 2000, 3000, 5000]
140036883512264
140037146633488

In [80]: x=[1,2,3,4,5,6]
x1=np.zeros(5)
np.append(x,np.append(x1,x))

#x1

Out[80]: array([ 1., 2., 3., 4., 5., 6., 0., 0., 0., 0., 0., 1., 2.,
3., 4., 5., 6.])

Mean finding
In [16]: import numpy as np
def mean(x):
b=np.sum(x)
y=b/len(x)
print(y)
return y

Calling function
In [17]: a=np.arange(6)
z=mean(a)

2.5

In [ ]:

3 of 3 30-07-2020, 09:16
4_Control Statements file:///C:/Users/Shyam/AppData/Local/Temp/4_Control Statements.html

TUTORIAL for Python Programming

Control Satements: Decision Making and Loops

Branch Statements
Conditional execution : if
Two way decision : if-else
Multi way decision : if-elif-if
Loop statements
Range based : for
Decision based : while

Conditional Execution
In [3]: # Example
temp = int(input("What is the temperature ? "));
if(temp > 35):
print(" Too hot !!")

What is the temperature ? 52


Too hot !!

Two way decisions


In [4]: # Example for finding roots of Quadratic Equation

import numpy as np

def quad_solv(a,b,c):
# This function determines the roots of a
# quadratic equation if they are real.
discrim = b*b - 4*a*c;
if(discrim >= 0):
sqrtdiscr = np.sqrt(discrim);
root1 = (-b + sqrtdiscr)/(2*a);
root2 = (-b - sqrtdiscr)/(2*a);
print ("Roots = ", root1, ",",root2);
else:
print ("No real roots" )
return;

In [ ]: ## Function Calling
a = int(input(" Enter the value of a="));
b = int(input(" Enter the value of b="));
c= int(input(" Enter the value of c="));
quad_solv(a,b,c)

1 of 4 30-07-2020, 09:14
4_Control Statements file:///C:/Users/Shyam/AppData/Local/Temp/4_Control Statements.html

In [10]: # Alternate method


(a,b,c) = [int(x) for x in input(" Input the coefficients(a,b,c):").split()]
quad_solv(a,b,c)

Input the coefficients(a,b,c):1 3 1


Roots = -0.3819660112501051 , -2.618033988749895

Multi way decisions


In [11]: # Example for determines the maximum of three numbers
def max3(x1,x2,x3):
# This function determines the maximum of three numbers
if(x1 > x2 and x1 > x3 ):
mx = x1;
elif ( x2 >= x1 and x2 >= x3 ):
mx = x2;
else:
mx = x3;
return mx

In [4]: print(max3(10,20,30))

print(max3(-10, -20, -30))

30
-10

For Loops
Most common loop is the "for" loop

the indexing is using range function

Examples

In [5]: for i in range(5):


print(i);

0
1
2
3
4

Note that the "i" ranges from 0 to 4 The last value is never included

Starting and ending values can be given with the syntax


range(start, end, increment)

2 of 4 30-07-2020, 09:14
4_Control Statements file:///C:/Users/Shyam/AppData/Local/Temp/4_Control Statements.html

In [6]: for i in range(3,11,2):


print (i);

3
5
7
9

Float values can be given with arange from numpy

In [9]: for i in np.arange(1.5,5,0.5):


print(i)

1.5
2.0
2.5
3.0
3.5
4.0
4.5

While Loop
This constructs repeatedly checks a condition and executes till it is true

In [12]: count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1

print ("Good bye!")

The count is: 0


The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

An optional else statement can be added to the while :

3 of 4 30-07-2020, 09:14
4_Control Statements file:///C:/Users/Shyam/AppData/Local/Temp/4_Control Statements.html

In [13]: count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
else:
print ("Loop Over")

print ("Good bye!")

The count is: 0


The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Loop Over
Good bye!

In [ ]:

4 of 4 30-07-2020, 09:14
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html

TUTORIAL for Python Programming


Matrices Operation

Array operation: Addition


In [43]: import numpy as np
x1=np.arange(0,3)
#x1=np.arange(3)
print(x1)
x2=np.arange(3,6)
print(x2)
np.add(x1, x2)

[0 1 2]
[3 4 5]

Out[43]: array([3, 5, 7])

In [32]: a = np.matrix('1 2 3; 4 5 6; 7 8 9')


print(a)
b= np.matrix('10 20 30; 40 50 60; 70 80 90')
print(b)
np.add(a, b)

[[1 2 3]
[4 5 6]
[7 8 9]]
[[10 20 30]
[40 50 60]
[70 80 90]]

Out[32]: matrix([[11, 22, 33],


[44, 55, 66],
[77, 88, 99]])

Matrix Addition using Nested Loop

Example
In Python, we can implement a matrix as a nested list (list inside a list). We can treat each element as a row of the matrix.

For example A = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. First row can be selected as A[0] and the element in first
row, first column can be selected as A[0[0].

We can perform matrix addition in various ways in Python. Here are a couple of them.

Write a program to add two matrices a and b

1 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html

In [21]: # This program is to add two given matrices


# We are using the concept of nested lists to represent matrix

# first matrix
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# second matrix
b = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# In this matrix we will store the sum of above matrices
# we have initialized all the elements of this matrix as zero
sum = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# iterating the matrix
# rows: number of nested lists in the main list
# columns: number of elements in the nested lists
for i in range(len(a)):
for j in range(len(a[0])):
sum[i][j] = a[i][j] + b[i][j]

# displaying the output matrix


for num in sum:
print(num)

[11, 22, 33]


[44, 55, 66]
[77, 88, 99]

Matrix Addition using Nested List Comprehension


In this case, we have used nested for loops to iterate through each row and each column. At each point, we add the
corresponding elements in the two matrices and store it in the result.

2 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html

In [34]: # This program is to add two given matrices


# We are using the concept of nested lists to represent matrix

# first matrix
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# second matrix
b = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# In this matrix we will store the sum of above matrices
# we have initialized all the elements of this matrix as zero
sum = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# iterating the matrix
# rows: number of nested lists in the main list
# columns: number of elements in the nested lists
result = [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]

for r in result:
print(r)

[11, 22, 33]


[44, 55, 66]
[77, 88, 99]

Array operation: Subtraction


In [27]: a = np.matrix('1 2 3; 4 5 6; 7 8 9')
print(a)
b= np.matrix('10 20 30; 40 50 60; 70 80 90')
print(b)
np.subtract(b, a)

[[1 2 3]
[4 5 6]
[7 8 9]]
[[10 20 30]
[40 50 60]
[70 80 90]]

Out[27]: matrix([[ 9, 18, 27],


[36, 45, 54],
[63, 72, 81]])

Write a program to subtract matrix 'a' from matrix 'b'

3 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html

In [28]: # This program is to subtrac two given matrices


# We are using the concept of nested lists to represent matrix

# first matrix
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# second matrix
b = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# In this matrix we will store the sum of above matrices
# we have initialized all the elements of this matrix as zero
sub = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# iterating the matrix
# rows: number of nested lists in the main list
# columns: number of elements in the nested lists
for i in range(len(a)):
for j in range(len(a[0])):
sub[i][j] = b[i][j] - a[i][j]

# displaying the output matrix


for num in sub:
print(num)

[9, 18, 27]


[36, 45, 54]
[63, 72, 81]

In [35]: # This program is to subtract two given matrices


# We are using the concept of nested lists to represent matrix

# first matrix
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# second matrix
b = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# In this matrix we will store the sum of above matrices
# we have initialized all the elements of this matrix as zero
sum = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# iterating the matrix
# rows: number of nested lists in the main list
# columns: number of elements in the nested lists
result = [[b[i][j] - a[i][j] for j in range(len(a[0]))] for i in range(len(a))]

for r in result:
print(r)

[9, 18, 27]


[36, 45, 54]
[63, 72, 81]

Array operation: Multiplication

4 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html

In [33]: import numpy as np


a = np.matrix('1 2 3; 4 5 6; 7 8 9')
print(a)
b= np.matrix('10 20 30; 40 50 60; 70 80 90')
print (b)
np.matmul(a, b)

[[1 2 3]
[4 5 6]
[7 8 9]]
[[10 20 30]
[40 50 60]
[70 80 90]]

Out[33]: matrix([[ 300, 360, 420],


[ 660, 810, 960],
[1020, 1260, 1500]])

Matrix Multiplication using Nested Loop


Multiplication of two matrices A and B is defined only if the number of columns in A is equal to the number of rows B.

If A is a n x m matrix and B is a m x l matrix then, AB is defined and has the dimension n x l (but BA is not defined). Here are a
couple of ways to implement matrix multiplication in Python.

In [37]: # Program to multiply two matrices using nested loops

# first matrix
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# second matrix
B = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# result is 3x4
mul_result = [[0,0,0],
[0,0,0],
[0,0,0]]

# iterate through rows of X


for i in range(len(A)):
# iterate through columns of A
for j in range(len(B[0])):
# iterate through rows of B
for k in range(len(Y)):
mul_result[i][j] += A[i][k] * B[k][j]

for r in mul_result:
print(r)

[300, 360, 420]


[660, 810, 960]
[1020, 1260, 1500]

5 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html

Matrix Multiplication Using Nested List Comprehension


In the above program, we have used nested for loops to iterate through each row and each column. We accumulate the sum
of products in the mu_result.

This technique is simple but computationally expensive as we increase the order of the matrix.

For larger matrix operations we recommend optimized software packages like NumPy which is several (in the order of 1000)
times faster than the above code.

In [53]: # Illustration of zip inbulit function


x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
list(zipped)

Out[53]: [(1, 4), (2, 5), (3, 6)]

In [1]: # # Program to multiply two matrices using list comprehension


# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]

# result is 3x4
result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in
X]

for r in result:
print(r)

[114, 160, 60, 27]


[74, 97, 73, 14]
[119, 157, 112, 23]

Matrix Power
In [2]: import numpy as np
import matplotlib.pyplot as pyplot
X = np.matrix('1 2 3; 4 5 6; 7 8 9')
print(X)
np.power(X, 2)

[[1 2 3]
[4 5 6]
[7 8 9]]

Out[2]: matrix([[ 1, 4, 9],


[16, 25, 36],
[49, 64, 81]], dtype=int32)

6 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html

Question: Write a program to to produce a new matrix whose elements are


the square of the elements of the matrix A
In [ ]: A = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]

Array operation: Division


In [18]: a = np.matrix('2 4 6; 4 8 6; 2 8 10')
print(a)
b= 2
print(b)
np.divide(a, b)

[[ 2 4 6]
[ 4 8 6]
[ 2 8 10]]
2

Out[18]: matrix([[ 1., 2., 3.],


[ 2., 4., 3.],
[ 1., 4., 5.]])

Matrix Inverse
In [20]: import numpy as np
import matplotlib.pyplot as pyplot
a = np.matrix('1 2 3; 4 5 6; 7 8 0')
print(a)
ainv = np.linalg.inv(a)
print (ainv)

[[1 2 3]
[4 5 6]
[7 8 0]]
[[-1.77777778 0.88888889 -0.11111111]
[ 1.55555556 -0.77777778 0.22222222]
[-0.11111111 0.22222222 -0.11111111]]

Question: Write a program to calculate inverse of a matrix X and also


compute product of inverse matrix and its original matrix
In [ ]: X=[[ 1 1 1]
[ 0 2 5]
[ 2 5 -1]]

In [ ]:

7 of 7 30-07-2020, 09:18

You might also like