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

Unit III Python

The document covers various advanced Python concepts including anonymous (lambda) functions, partial functions, and generators, explaining their syntax and usage with examples. It also introduces NumPy, a library for numerical computing, detailing how to create and manipulate arrays, including different dimensions, indexing, slicing, and data types. Key differences between generator functions and normal functions are highlighted, along with methods for checking and converting data types in NumPy arrays.

Uploaded by

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

Unit III Python

The document covers various advanced Python concepts including anonymous (lambda) functions, partial functions, and generators, explaining their syntax and usage with examples. It also introduces NumPy, a library for numerical computing, detailing how to create and manipulate arrays, including different dimensions, indexing, slicing, and data types. Key differences between generator functions and normal functions are highlighted, along with methods for checking and converting data types in NumPy arrays.

Uploaded by

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

Unit – III

The Anonymous(Lambda) Functions:

These functions are called anonymous because they are not declared in the standard manner by using
the def keyword. lambda keyword is used to create small anonymous functions.
 Lambda forms can take any number of arguments but return just one value in the form of an
expression. They cannot contain commands or multiple expressions.
 An anonymous function cannot be a direct call to print because lambda requires an expression
 Lambda functions have their own local namespace and cannot access variables other than those in
their parameter list and those in the global namespace.

Syntax

The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]] : expression

For Example1

sum=lambda arg1, arg2 : arg1 + arg2;


print("Value of total : ", sum(10,20))
print("Value of total : ", sum(20,20))

Output
30
40

For Example2

a=lambdab:b+15;
print(a(15))

Output
30

For Example3

a=lambdab, c:b*c;
print(a(6,5))

Output
30

Partial Argument Application (Partial Function):

Partial functions allow user to fix a certain number of arguments of a function and generate a new
function.Partial functional application in python is implemented through functools library.
For Example 1

fromfunctools import partial

def f(a, b, c, x):


d = 10*a + 5*b + 2*c + x
returnd

g = partial(f, 3, 1, 4)
print(g(5))

Output
48

For Exampl 2

fromfunctools import *

defadd(a, b, c):
d = 10*a + 5*b + c
returnd

g = partial(add, c = 2, b = 5)
print(g(5))

Output
77

Python Generators:

A generator is a function that returns an iterator that produces a sequence of values when iterated over. It
traverses the entire items at once.A generator function is similar to a regular function, but instead of a return
statement, it has a yield keyword.Generators are useful when user wants to produce a large sequence of
values, but don't want to store all of them in memory at once.If there is no value found in iteration, it
raises StopIteration exception.

Generally generators in Python −


 Defined with the def keyword
 Use the yield keyword
 May contain several yield keywords.
 Returns an iterator.

Because the values from the generator object are fetched one at a time rather than the entire list at once, so
user can use a for-loop, next(), or list() function to get the actual values.

Syntax

defgenerator_name(arguments) :
statements
.
.
yield<value/variable>
For Example 1 Write a program to print the table of the given number using the generator.

def table(n):
for i in range(1,11):
yield n*i

for i in table(15):
print(i)

For Example 2 Working with multiple yield statements

def multiple_yield():
str1 = "First String"
yield str1

str2 = "Second string"


yield str2

str3 = "Third String"


yield str3

obj = multiple_yield()
print(next(obj))
print(next(obj))
print(next(obj))

Difference between yield and return

The difference between yield and return is that yield returns a value and pauses the execution while
maintaining the internal states, whereas the return statement returns a value and terminates the execution
of the function.

Difference between Generator function and Normal function


o Normal function contains only one return statement whereas generator function can contain one or
more yield statement.
o When the generator functions are called, the normal function is paused immediately and control
transferred to the caller.
o Local variable and their states are remembered between successive calls.
o StopIteration exception is raised automatically when the function terminates.
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.The array object in NumPy is
called ndarray. NumPy was created in 2005 by Travis Oliphant.

Import NumPy

Once NumPy is installed, it can be imported in the application by adding the import keyword.

import numpy

For Example

import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)

NumPy as np

NumPy is usually imported under the np alias. In Python alias are an alternate name for referring to the same
thing.

Syntax

import <package name> as <alias name>

For Example

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

Create a NumPyndarray Object

NumPy is used to work with arrays. The array object in NumPy is called ndarray.NumPy ndarray object is
created by using the array() function.To create an ndarray, a list, tuple or any array-like object is passed
into the array() method, and it will be converted into an ndarray.

For Example 1 Creating NumPy array using tuple

import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
For Example 2 Creating NumPy array using list

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

Dimensions in Arrays

A dimension in arrays is one level of array depth (nested arrays).

(1) 0-D Arrays

0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.

import numpy as np
arr = np.array(42)
print(arr)

(2) 1-D Arrays

An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

(3) 2-D Arrays

An array that has 1-D arrays as its elements is called a 2-D array.These are often used to represent
matrix or 2nd order tensors.

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)

(4) 3-D Arrays

An array that has 2-D arrays (matrices) as its elements is called 3-D array.These are often used to
represent a 3rd order tensor.

import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)

Checking Number of Dimensions

NumPy Arrays provides the ndim attribute that returns an integer that tells how many dimensions the array
have.
import numpy as np

a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)

NumPy Array Indexing

Array indexing is the same as accessing an array element. An array element can access by referring to its
index number.The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the
second has index 1 etc.

For Example Get the first element from the following array(1D):
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])

 Access 2-D Arrays

To access elements from 2-D arrays we can use comma separated integers representing the
dimension and the index of the element.

For Example Access the element on the first row, second column:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('2nd element on 1st row: ', arr[0, 1])

 Access 3-D Arrays

To access elements from 3-D arrays we can use comma separated integers representing the
dimensions and the index of the element.

For Example Access the third element of the second array of the first array:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
Negative Indexing

Use negative indexing to access an array from the end.

For Example: Print the last element from the 2-D array

import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('Last element from 2nd dim: ', arr[1, -1])

NumPy Array Slicing

Slicing in python means taking elements from one given index to another given index.In other words Slicing
NumPy arrays means extracting elements from an array in a specific range.NumPy arrays use
brackets [] and : notations for slicing.

Syntax

[start:end:step]

The default value of start is 0, step is 1 and end is length of array in that dimension.

Different slicing expressions are as follows:

Slicing Expression Meaning

a[m:n] Select elements with an index starting at m and ending at n-1.

a[:n] Select elements starting with index 0 and up to element with index n-1

a[m:] Select elements starting with index m and up to the last element

a[m:n:k] Select elements with index m through n (exclusive), with an increment k

a[::-1] Select all elements in reverse order

For Example 1 Slice elements from index 1 to index 5 from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])
For Example2 Slice elements from index 4 to the end of the array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])

For Example3 Slice elements from beginning to index 4 (not included):


import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[:4])

For Example4 Slice elements from index 2 to index 6(not included) with a step value 2:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[2:6:2])

Negative Slicing

Use the minus operator to refer to an index from the end.

For Example Slice from the index 3from the end to index 1from the end:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])

Slicing 2-D Arrays


To slice a multidimensional array, apply the square brackets [] and the : notation to each dimension (or
axis). The slice returns a reduced array where each element matches the selection rules.

For Example 1 From the second element, slice elements from index 1 to index 4(not included)
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])

For Example 2 From both elements, return index 2


import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 2])
For Example 3 From both elements, slice index 1 to index 4 (not included), this will return a 2-D
array:
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[0:2, 1:4])

Data Types in NumPy

NumPy has some extra data types, and refer to data types with one character, like i for integers, u for
unsigned integers etc.

Below is a list of all data types in NumPy and the characters used to represent them.

 i - integer
 b - boolean
 u - unsigned integer
 f - float
 c - complex float
 m - timedelta
 M - datetime
 O - object
 S - string
 U - unicode string
 V - fixed chunk of memory for other type ( void )

Checking the Data Type of an Array

The NumPy array object has a property called dtype that returns the data type of the array:

For Example Get the data type of an array object

import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.dtype)

Creating Arrays With a Defined Data Type

The array( ) function is used to create arrays, this function can take an optional argument: dtype that
allows to define the expected data type of the array elements:

For Example Create an array with data type String

import numpy as np
arr = np.array([1, 2, 3, 4], dtype='S')
print(arr)
print(arr.dtype)
If a type is given in which elements can't be casted then NumPy will raise a ValueError.

import numpy as np
arr = np.array(['a', '2', '3'], dtype='i')

A non integer string like ‘a’ can not be converted to integer (will raise an error).

Converting Data Type on Existing Arrays

The best way to change the data type of an existing array, is to make a copy of the array with
the astype() method.

The astype() function creates a copy of the array, and allows to specify the data type as a parameter.

The data type can be specified using a string, like 'f' for float, 'i' for integer etc. or can use the data type
directly like float for float and int for integer.

For Example 1 Change data type from float to integer by using ‘i' as parameter

import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype('i')
print(newarr)
print(newarr.dtype)

For Example 2 Change data type from float to integer by using ‘int' as parameter

import numpy as np
arr = np.array([1.1, 2.1, 3.1])
newarr = arr.astype(int)
print(newarr)
print(newarr.dtype)

For Example 3 Change data type from integer to boolean

import numpy as np
arr = np.array([1, 0, 3])
newarr = arr.astype(bool)
print(newarr)
print(newarr.dtype)

NumPy Array Copy vs View

COPY: The copy owns the data and any changes made to the copy will not affect original array, and
any changes made to the original array will not affect the copy.
For Example Make a copy, change the original array, and display both arrays

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy( )
arr[0] = 42
print(arr)
print(x)

VIEW: The view does not own the data and any changes made to the view will affect the original
array, and any changes made to the original array will affect the view.

For Example Make a view, change the original array, and display both arrays

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.view( )
arr[0] = 42
print(arr)
print(x)

Check if Array Owns its Data

Every NumPy array has the attribute base that returns None if the array owns the data. Otherwise,
the base attribute refers to the original object.

For Example Print the value of the base attribute to check if an array owns it’s data or not

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
x = arr.copy( )
y = arr.view( )
print(x.base)
print(y.base)

NumPy Array Shape

The shape of an array is the number of elements in each dimension. NumPy arrays have an attribute
called shape that returns a tuple with each index having the number of corresponding elements.

For Example Print the shape of a 2-D array

import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
It returns (2, 4), which means that the array has 2 dimensions, where the first dimension has 2 elements and
the second has 4.

NumPy Array Reshaping

Reshaping means changing the shape of an array. By reshaping we can add or remove dimensions or change
number of elements in each dimension.

For Example Reshape From 1-D to 2-D

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
print(newarr)

It returns a 2-D array where outermost dimension will have 4 arrays, each with 3 elements.

Arithmetic with NumPy arrays


Python has a wide range of standard arithmetic operations. These operations help perform normal functions
of addition, subtraction, multiplication, and divisions. There are specific functions in NumPy for performing
arithmetic operations. Arithmetic operations are possible only if the array has the same structure and
dimensions.

Addition

The add( ) function sums the content of two arrays, and return the results in a new array.

import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.add(arr1, arr2)
print(newarr)

Subtraction

The subtract( ) function subtracts the values from one array with the values from another array, and
return the results in a new array.

import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.subtract(arr1, arr2)
print(newarr)
Multiplication

The multiply( ) function multiplies the values from one array with the values from another array, and
return the results in a new array.

import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.multiply(arr1, arr2)
print(newarr)

Division

The divide( ) function divides the values from one array with the values from another array, and
return the results in a new array.

import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.divide(arr1, arr2)
print(newarr)

Power

The power( ) function rises the values from the first array to the power of the values of the second
array, and return the results in a new array.

import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.power(arr1, arr2)
print(newarr)

Remainder

Both the mod( ) and the remainder( ) functions return the remainder of the values in the first array
corresponding to the values in the second array, and return the results in a new array.

import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.mod(arr1, arr2)
print(newarr)
Psuedorandom number generation

Python defines a set of functions that are used to generate or manipulate random numbers through
the random module.

Random numbers generated through a generation algorithm are called pseudo random. Functions in the
random module rely on a pseudo-random number generator function random( ), which generates a
random float number between 0.0 and 1.0. These particular type of functions is used in a lot of games,
lotteries, or any application requiring a random number generation.

Generate Random Number

NumPy offers the random module to work with random numbers. The randint( ) method is used to generate
random integer numbers.

For Example Generate random integer from 0 to 100

from numpy import random


x = random.randint(100)
print(x)

Generate Random Float

The random module's rand( ) method returns a random float between 0 and 1.

For Example Generate random float from 0 to 1

from numpy import random


x = random.rand( )
print(x)

Generate Random Array


Integers

The randint( ) method takes a size parameter where you can specify the shape of an array.

For Example 1 Generate a 1-D array containing 5 random integers from 0 to 100

from numpy import random


x=random.randint(100, size=(5))
print(x)

For Example 2 Generate a 2-D array with 3 rows, each row containing 5 random integers from 0 to 100

from numpy import random


x = random.randint(100, size=(3, 5))
print(x)
Floats

The rand( ) method also allows you to specify the shape of the array.

For Example 1 Generate a 1-D array containing 5 random floats

from numpy import random


x = random.rand(5)
print(x)

For Example 2 Generate a 2-D array with 3 rows, each row containing 5 random float numbers

from numpy import random


x = random.rand(3, 5)
print(x)

Generate Random Number From Array

The choice( ) method allows to generate a random value based on an array of values. The choice(
) method takes an array as a parameter and randomly returns one of the values.

For Example Return one of the values in an array

from numpy import random


x = random.choice([3, 5, 7, 9])
print(x)

The choice( ) method also allows to return an array of values. Add a size parameter to specify the shape
of the array.

For Example Generate a 2-D array that consists of the values in the array parameter (3, 5, 7, and 9)

from numpy import random


x = random.choice([3, 5, 7, 9], size=(3, 5))
print(x)

Using random.sample( )

The random module also provides the sample( ) method, which directly generates a list of random numbers.

For Example

import random
#Generate 5 random numbers between 10 and 30
random_list = random.sample(range(10, 40), 6)
print(random_list)
Classes & Objects

Python is an object oriented programming language. Almost everything in Python is an object, with its
properties and methods.

Class

The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and
methods. The keyword class is used for creating classes.

Syntax:
class <class_name> :
statement 1
.
.
.
Statement n
Example:
class bike:
gear = 0
name = “TVS”

Class creates a user-defined data structure, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a blueprint for an
object.
Some points on Python class:
 Classes are created by keyword class.
 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator.

Objects

The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard,
chair, table, pen, etc.

Syntax:
<object_name> = class_name(<arguments>)

Example:
class bike:
gear = 0
name = “TVS”
# object creation
b = bike( )
print(b.name)

Methods

The method is a function that is associated with an object. In Python, a method is not unique to class
instances. Any object type can have methods.
Example:
# create a class
class room:
length = 0.0
breadth = 0.0

# method to calculate area

def cal_area(self) :
area = self.length * self.breadth
print(“Area of Room = “, area)

# create object of room class


study_room = room( )

# assign values to all the attributes


study_room.length = 42.5
study_room.breadth = 30.8

# access method inside class


study_room.cal_area( )

Constructors in Python

Constructors are generally used for instantiating an object. The task of constructors is to initialize(assign
values) to the data members of the class when an object of the class is created. In Python the __init__( )
method is called the constructor and is always called when an object is created. It accepts the self-keyword
as a first argument which allows accessing the attributes or method of the class.

Syntax:
def __init__(self) :
statements

Types of constructors :

 Default constructor: The default constructor is a simple constructor which doesn’t accept any
arguments. Its definition has only one argument which is a reference to the instance being constructed.

class student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")

def show(self,name):
print("Hello", name)

student = student1( )
student.show("John")
 Parameterized constructor: Constructor with parameters is known as parameterized constructor. The
parameterized constructor takes its first argument as a reference to the instance being constructed
known as self and the rest of the arguments are provided by the programmer.

class student:
# Constructor - non parameterized
def __init__(self, name):
self.name = name
print("This is non parametrized constructor")

def show(self):
print("Hello", self.name)

student = student1( “John”)


student.show( )

You might also like