0% found this document useful (0 votes)
7 views11 pages

Unit 3 Bca Python

Functions: Anonymous (Lambda) Functions, Partial Argument Application, Generators. Objects and Methods in Python. NumPy: creating N-dimensional arrays, arithmetic with NumPy arrays, basic indexing and slicing, Psuedorandom number generation.

Uploaded by

mybzns.124
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views11 pages

Unit 3 Bca Python

Functions: Anonymous (Lambda) Functions, Partial Argument Application, Generators. Objects and Methods in Python. NumPy: creating N-dimensional arrays, arithmetic with NumPy arrays, basic indexing and slicing, Psuedorandom number generation.

Uploaded by

mybzns.124
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BCA SEM- 4 PYTHON WEBSOL UNIT - 3

Unit III

Functions: Anonymous (Lambda) Functions, Partial Argument Application,


Generators. Objects and Methods in Python. NumPy: creating N-dimensional arrays,
arithmetic with NumPy arrays, basic indexing and slicing, Psuedorandom number
generation.

Lambda Functions
Python Lambda Functions are anonymous functions means that the function is without a
name. As we already know the def keyword is used to define a normal function in Python.
Similarly, the lambda keyword is used to define an anonymous function in Python.

The power of lambda is better shown when you use them as an anonymous function inside
another [Link] you have a function definition that takes one argument, and that
argument will be multiplied with an unknown number:

Python Lambda Function Syntax


Syntax: lambda arguments : expression
 lambda: The keyword to define the function.
 arguments: A comma-separated list of input parameters (like in a regular function).
 expression: A single expression that is evaluated and returned.

Difference Between lambda and def Keyword


lambda is concise but less powerful than def when handling complex logic. Let's take a
look at short comparison between the two:
Feature lambda Function Regular Function (def)

Definition Single expression with lambda. Multiple lines of code.

Anonymous (or named if


Name Must have a name.
assigned).

Statements Single expression only. Can include multiple statements.

Documentation Cannot have a docstring. Can include docstrings.

Best for short, temporary Better for reusable and complex


Reusability
functions. logic.

Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page | 1


BCA SEM- 4 PYTHON WEBSOL UNIT - 3

# Using lambda # Using def


sq = lambda x: x ** 2 def sqdef(x):
print(sq(3)) return x ** 2
print(sqdef(3))
# Example: Perform addition and x = lambda a : a + 10
multiplication in a single line print(x(5))
calc = lambda x, y: (x + y, x * y)

res = calc(3, 4)
print(res)
x = lambda a, b : a * b x = lambda a, b, c : a + b + c
print(x(5, 6)) print(x(5, 6, 2))

Partial Argument Application


Partial argument application in Python involves creating a new function from an existing one
by "fixing" or pre-setting some of its arguments to specific values. This technique is also
known as partial function application or currying. The primary way to achieve this in Python
is by using the [Link] object.

Here's how [Link] works:


 Import partial: Begin by importing the partial object from the functools module:
Benefits of Partial Argument Application:
 Code Reusability:
Create specialized versions of general functions without modifying the original.
 Conciseness:
Reduce redundant argument passing when certain arguments are consistently used.
 Functional Programming:
Facilitates a more functional programming style by enabling the creation of new functions
from existing ones.
 Callbacks:
Useful in scenarios where callback functions need to carry pre-determined data or context.

from functools import partial from functools import *

# A normal function # A normal function


def f(a, b, c, x): def add(a, b, c):
return 1000*a + 100*b + 10*c + x return 100 * a + 10 * b + c

Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page | 2


BCA SEM- 4 PYTHON WEBSOL UNIT - 3

# A partial function that calls f with # A partial function with b = 1 and c = 2


# a as 3, b as 1 and c as 4. add_part = partial(add, c = 2, b = 1)
g = partial(f, 3, 1, 4)
# Calling partial function
# Calling g() print(add_part(3))
print(g(5))

Generators in Python
a generator is a function that returns an iterator that produces a sequence of values when
iterated over.

A generator function is a special type of function that returns an iterator object. Instead of
using return to send back a single value, generator functions use yield to produce a series of
results over time. This allows the function to generate values and pause its execution after
each yield, maintaining its state between iterations.

the yield keyword is used to produce a value from the generator.

Why Do We Need Generators?


 Memory Efficient : Handle large or infinite data without loading everything into
memory.
 No List Overhead : Yield items one by one, avoiding full list creation.
 Lazy Evaluation : Compute values only when needed, improving performance.
 Support Infinite Sequences : Ideal for generating unbounded data like Fibonacci
series.
 Pipeline Processing : Chain generators to process data in stages efficiently.

Yield vs Return
 Yield: is used in generator functions to provide a sequence of values over time. When
yield is executed, it pauses the function, returns the current value and retains the state of
the function. This allows the function to continue from same point when called again,
making it ideal for generating large or complex sequences efficiently.
 Return: is used to exit a function and return a final value. Once return is executed,
function is terminated immediately and no state is retained. This is suitable for cases
where a single result is needed from a function.

With return
def fun(): sq = (x*x for x in range(1, 6))
return 1 + 2 + 3 for i in sq:
print(i)
res = fun()
print(res)

Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page | 3


BCA SEM- 4 PYTHON WEBSOL UNIT - 3

6 1
4
9
16
25

object
In Python, an object is an instance of a class, which serves as a blueprint for creating
objects. Objects encapsulate both data (attributes) and behavior (methods).

Methods are functions defined within a class that define the actions or behaviors an object
can perform. They operate on the object's attributes or interact with other objects. Methods
are called using dot notation.

The __init__() Method

The examples above are classes and objects in their simplest form, and are not really useful in
real life applications.

To understand the meaning of classes we have to understand the built-in __init__() method.

All classes have a method called __init__(), which is always executed when the class is being
initiated.

Use the __init__() method to assign values to object properties, or other operations that are
necessary to do when the object is being created:

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

p1 = Person("John", 36)

print([Link])
print([Link])

Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page | 4


BCA SEM- 4 PYTHON WEBSOL UNIT - 3

Methods in Python

In Python, a method is a function that belongs to a class and operates on objects (instances) of
that class. Methods define the behavior and actions that an object can perform. They are a
fundamental concept in object-oriented programming (OOP) in Python.

There are three main types of methods in Python:


 Instance Methods:
o These are the most common type of methods.
o They operate on a specific instance of a class and can access and modify the instance's
attributes.
o The first parameter of an instance method is conventionally named self, which refers to the
instance itself.
class Dog:
def __init__(self, name):
[Link] = name

def speak(self): # Instance method


return f"{[Link]} says Woof!"

 Class Methods:
o These methods are associated with the class itself, not a specific instance.
o They can access and modify class-level attributes, but not instance-specific attributes directly.
o They are defined using the @classmethod decorator and take cls (conventionally) as their
first parameter, which refers to the class.

NumPy
NumPy is a Python library used for working with arrays.

It also has functions for working in domain of linear algebra, fourier transform, and matrices.

NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use
it freely.

NumPy stands for Numerical Python.

Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page | 5


BCA SEM- 4 PYTHON WEBSOL UNIT - 3

Numpy is a general-purpose array-processing package. It provides a high-performance


multidimensional array object, and tools for working with these arrays. It is the
fundamental package for scientific computing with Python.

Arrays in Numpy
Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a
tuple of positive integers. In Numpy, number of dimensions of the array is called rank of
the array. A tuple of integers giving the size of the array along each dimension is known as
shape of the array. An array class in Numpy is called as ndarray.

Attributes of ndarray
Understanding the attributes of an ndarray is important while working
with NumPy effectively. Here are the key attributes:
1. [Link]: Returns a tuple representing the shape (dimensions) of the array.
2. [Link]: Returns the number of dimensions (axes) of the array.
3. [Link]: Returns the total number of elements in the array.
4. [Link]: Provides the data type of the array elements.
5. [Link]: Returns the size in bytes of each element

import numpy as np Shape: (2, 3)


arr = [Link]([[1, 2, 3], [4, 5, 6]]) Dimensions: 2
Size: 6
print("Shape:", [Link]) Data type: int64
print("Dimensions:", [Link]) Item size: 8
print("Size:", [Link])
print("Data type:", [Link])
print("Item size:", [Link])

NumPy is used to work with arrays. The array object in NumPy is called ndarray.

We can create a NumPy ndarray object by using the array() function.

import numpy as np [1 2 3 4 5]
arr = [Link]([1, 2, 3, 4, 5]) <class '[Link]'>
print(arr)
print(type(arr))
import numpy as np
arr = [Link]((1, 2, 3, 4, 5)) [1 2 3 4 5]
print(arr)
import numpy as np [[1 2 3]
arr = [Link]([[1, 2, 3], [4, 5, 6]]) [4 5 6]]
print(arr)

Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page | 6


BCA SEM- 4 PYTHON WEBSOL UNIT - 3

Addition of Arrays
Addition is an arithmetic operation where the corresponding elements of two arrays are
added together. In NumPy the addition of two arrays is done using the [Link]() function.
import numpy as np [ 7 77 23 130]

a = [Link]([5, 72, 13, 100])


b = [Link]([2, 5, 10, 30])

add_ans = [Link](a, b)
print(add_ans)

Indexing:
Array indexing is the same as accessing an array element.

You can access an array element 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.

1
import numpy as np

arr = [Link]([1, 2, 3, 4])

print(arr[0])

30
import numpy as np

arr = [Link]([10, 20, 30, 40, 50])

print(arr[2])

Slicing arrays
Slicing in python means taking elements from one given index to another given index.

We pass slice instead of index like this: [start:end].

Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page | 7


BCA SEM- 4 PYTHON WEBSOL UNIT - 3

We can also define the step, like this: [start:end:step].

If we don't pass start its considered 0

If we don't pass end its considered length of array in that dimension

If we don't pass step its considered 1

import numpy as np [2 3 4 5]

arr = [Link]([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5])
import numpy as np [5 6 7]

arr = [Link]([1, 2, 3, 4, 5, 6, 7])

print(arr[4:])

Negative Slicing

import numpy as np
7

arr = [Link]([1, 2, 3, 4, 5, 6, 7])

print(arr[-1])

import numpy as np [4 5 6]

arr = [Link]([1, 2, 3, 4, 5, 6, 7])

print(arr[-4:-1])
import numpy as np [2 4]

arr = [Link]([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5:2])

Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page | 8


BCA SEM- 4 PYTHON WEBSOL UNIT - 3

Random Number
Random number does NOT mean a different number every time. Random means something
that can not be predicted logically.

If there is a program to generate random number it can be predicted, thus it is not truly
random.

Random numbers generated through a generation algorithm are called pseudo random.

NumPy offers the random module to work with random numbers.

from numpy import random 62

x = [Link](100)

print(x)

In NumPy we work with arrays, and you can use the two methods from the above examples
to make random arrays.

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

from numpy import random [56 61 90 8 7]

x=[Link](100, size=(5))

print(x)

Using '[Link]()'
The [Link]() method is used to generate the random numbers. It is done with the help
of a pseudo-random number generator by performing some operation on the given value. The
random module creates a random number in Python using the seed value as a base.
import random # Seed with a specific value 0.5714025946899135
[Link](10) # Will always produce the 0.4745706786885481
same output if seeded with 10(base)
print([Link]()) [Link](12)
print([Link]())

Pseudo Random Number Generator(PRNG) refers to an algorithm that uses


mathematical formulas to produce sequences of random numbers. PRNGs generate a

Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page | 9


BCA SEM- 4 PYTHON WEBSOL UNIT - 3

sequence of numbers approximating the properties of random numbers. A PRNG starts


from an arbitrary starting state using a seed state.

Applications of PRNG
PRNGs are suitable for applications where many random numbers are required and where it
is useful that the same sequence can be replayed easily. Popular examples of such
applications are simulation and modeling applications. PRNGs are not suitable for
applications where it is important that the numbers are really unpredictable, such as data
encryption and gambling.

# Python3 code to implement the 3 7 0 9 8


# approach
import random
from datetime import datetime

# Passing the current time as the seed value


[Link]([Link]())

for i in range(5):
print([Link](0, 10), end="\t")

# This code is contributed by phasing17

Pseudorandom Number Generator using NumPy


 The pseudo-random number is a partial random number, not a ‘truly’ random number. These
are computer-generated numbers (pre-determined) that look random.
 These algorithms are a set of algorithms created by Computer Scientists to generate pseudo-
random numbers (approximates).
 Seed functions use for generate random numbers, based on “pseudo-random number
generators” algorithms.

Random Seed Importance


 NumPy random () function based on some value called a seed value.
 Numpy. random. seed () method initialized a Random State and generator is re-seeded.
 The same seed value runs to the same random number generation even on different machines
given the environment remains the same.

Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page | 10


BCA SEM- 4 PYTHON WEBSOL UNIT - 3

 functions used to compute uniform, normal (Gaussian), lognormal, negative exponential,


gamma, and beta distributions. For generating distributions of angles, the von Mises
distribution is available.
 Table:- Partial list of [Link] functions

Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM -4 Page | 11

You might also like