Ilovepdf Merged 5
Ilovepdf Merged 5
EXPERIMENT 1:
1
Name:- Pranav Ravindra Patil PRN:- 220105131328
RESULT / OUTPUT:
In the above result, math.gcd() function generates the GCD of two given numbers. In
the gcd() function, a and b pass as an argument that returns the greatest common divisor
of two integer numbers, completely dividing the numbers.
2
Name:- Pranav Ravindra Patil PRN:- 220105131328
EXPERIMENT 2
TITLE: Implement a Python Program to find the largest number from a list of numbers
THEORY: In this program, we need to find out the largest element present in the array and
display it. This can be accomplished by looping through the array from start to end by
comparing max with all the elements of an array. If any of element is greater than max, then
store a value of the element in max. Initially, max will hold the value of the first element. At
the end of the loop, max represents the largest element in the array.
In the above array, initially, max will hold the value 25. In the 1st iteration, max will be
compared with 11, since 11 is less than max. Max will retain its value. In the next iteration, it
will be compared to 7, 7 is also less than max, no change will be made to the max. Now, max
will be compared to 75. 75 is greater than max so that max will hold the value of 75.
Continue this process until the end of the array is reached. At the end of the loop, max will
hold the largest element in the array.
ALGORITHM:
● STEP 3: Loop through the array from 0 to length of the array and compare the value
of max with elements of the array.
● STEP 4: If any element is greater than max, max will hold the value of that element.
● STEP 5: At last, max will hold the largest element in the array.
3
Name:- Pranav Ravindra Patil PRN:- 220105131328
PROCEDURE / CODE:
arr=[54,9,12,69,43]
RESULT/OUTPUT:
4
Name:- Pranav Ravindra Patil PRN:- 220105131328
EXPERIMENT 3
THEORY: Python is one of the most popular and powerful languages. It takes a few lines to
execute the code, which makes it much user-friendly language. In this tutorial, we will learn
the linear search in Python. Searching is a technique to find the particular element is present or
not in the given list.
● Linear Search
● Binary Search
Both techniques are widely used to search an element in the given list.
Linear search is a method of finding elements within a list. It is also called a sequential
search. It is the simplest searching algorithm because it searches the desired element in a
sequential manner. It compares each and every element with the value that we are searching
for. If both are matched, the element is found, and the algorithm returns the key's index
position.
Let's understand the following steps to find the element key = 7 in the given list.
Step - 1: Start the search from the first element and Check key = 7 with each element of list x.
5
Name:- Pranav Ravindra Patil PRN:- 220105131328
1. LinearSearch(list, key)
2. for each item in the list
3. if item == value
4. return its index position
5. return -1
6
Name:- Pranav Ravindra Patil PRN:- 220105131328
PROGRAM / CODE:
if result == -1:
print("Element not found")
else:
print(f"Element found at index: {result}")
RESULT/OUTPUT:
Explanation:
In the above code, we have created a function linear_Search(), which takes three
arguments - list1, length of the list, and number to search. We defined for loop and iterate
each element and compare to the key value. If element is found, return the index else
return -1 which means element is not present in the list.
7
Name:- Pranav Ravindra Patil PRN:- 220105131328
EXPERIMENT 4
THEORY: A binary search is an algorithm to find a particular element in the list. Suppose we
have a list of thousand elements, and we need to get an index position of a particular
element. We can find the element's index position very fast using the binary search algorithm.
There are many searching algorithms but the binary search is most popular among them.
The elements in the list must be sorted to apply the binary search algorithm. If elements are
not sorted then sort them first.
Concept of Binary Search
In the binary search algorithm, we can find the element position using the following methods.
● Recursive Method
● Iterative Method
The divide and conquer approach technique is followed by the recursive method. In this method, a
function is called itself again and again until it found an element in the list.
A set of statements is repeated multiple times to find an element's index position in the iterative
method. The while loop is used for accomplish this task.
Binary search is more effective than the linear search because we don't need to search each list
index. The list must be sorted to achieve the binary search algorithm.
We have a sorted list of elements, and we are looking for the index position of 45.
So, we are setting two pointers in our list. One pointer is used to denote the smaller value
called low and the second pointer is used to denote the highest value called high.
1. mid = (low+high)/2
2. Here, the low is 0 and the high is 7.
3. mid = (0+7)/2
4. mid = 3 (Integer)
8
Name:- Pranav Ravindra Patil PRN:- 220105131328
Now, we will compare the searched element to the mid index value. In this case, 32 is not equal to
45. So we need to do further comparison to find the element.
If the number we are searching equal to the mid. Then return mid otherwise move to the further comparison.
The number to be search is greater than the middle number, we compare the n with the middle
element of the elements on the right side of mid and set low to low = mid + 1.
Otherwise, compare the n with the middle element of the elements on the left side of mid and
set high to high = mid - 1.
9
Name:- Pranav Ravindra Patil PRN:- 220105131328
PROCEDURE/CODE:
FOR ITERATIVE BINARY SEARCH METHOD:
# Iterative Binary Search Function
def binary_search(list1, n):
low = 0
high = len(list1) - 1
# Initial list1
list1 = [12, 32, 48, 54, 60, 68, 80]
n = 48
# Function call
result = binary_search(list1, n)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in list1")
10
Name:- Pranav Ravindra Patil PRN:- 220105131328
# Test list1ay
list1 = [12, 32, 48, 54, 60, 68, 80]
n = 54
res = binary_search(list1, 0, len(list1) - 1, n)
if res != -1:
print("Element is present at index", str(res))
else:
print("Element is not present in list1")
11
Name:- Pranav Ravindra Patil PRN:- 220105131328
RESULT/OUTPUT:
FOR ITERATIVE BINARY SEARCH METHOD
CONCLUSION:
A binary search algorithm is the most efficient and fast way to search an element in
the list. It skips the unnecessary comparison. As the name suggests, the search is
divided into two parts. It focuses on the side of list, which is close to the number
that we are searching.
We have discussed both methods to find the index position of the given number.
12
Name:- Pranav Ravindra Patil PRN:- 220105131328
SOCSE, Sandip University, Nashik
EXPERIMENT 5
THEORY: The Insertion sort is a straightforward and more efficient algorithm than the
previous bubble sort algorithm. The insertion sort algorithm concept is based on the deck of
the card where we sort the playing card according to a particular card. It has many
advantages, but there are many efficient algorithms available in the data structure.
While the card-playing, we compare the hands of cards with each other. Most of the player
likes to sort the card in the ascending order so they can quickly see which combinations they
have at their disposal.
The insertion sort implementation is easy and simple because it's generally taught in the
beginning programming lesson. It is an in-place and stable algorithm that is more beneficial
for nearly-sorted or fewer elements.
The insertion sort algorithm is not so fast because of it uses nested loop for sort the elements.
● In-place: The in-place algorithm requires additional space without caring for the
input size of the collection. After performing the sorting, it rewrites the original
memory locations of the elements in the collection.
● Stable: The stable is a term that manages the relative order of equal objects from the
initial array.
The more important thing, the insertion sort doesn't require to know the array size in advance
and it receives the one element at a time.
The great thing about the insertion sort is if we insert the more elements to be sorted - the
algorithm arranges the in its proper place without performing the complete sort.
It is more efficient for the small (less than 10) size array. Now, let's understand the concepts
of insertion sort.
13
Name:- Pranav Ravindra Patil PRN:- 220105131328
SOCSE, Sandip University, Nashik
The Concept of Insertion Sort
The array spilled virtually in the two parts in the insertion sort - An unsorted part and sorted
part.
The sorted part contains the first element of the array and other unsorted subpart contains the
rest of the array. The first element in the unsorted array is compared to the sorted array so
that we can place it into a proper sub-array.
It focuses on inserting the elements by moving all elements if the right-side value is smaller
than the left side.
It will repeatedly happen until the all element is inserted at correct place.
To sort the array using insertion sort below is the algorithm of insertion sort.
We will consider the first element in the sorted array in the following array.
[10, 4, 25, 1, 5]
4, 25, 1, 5]
Now we take the first element from the unsorted array - 4. We store this value in a new
variable temp. Now, we can see that the 10>4 then we move the 10 to the right and that
overwrite the 4 that was previously stored.
Here the 4 is lesser than all elements in sorted subarray, so we insert it at the first index
position.
14
Name:- Pranav Ravindra Patil PRN:- 220105131328
Again we check the number 1. We save it in temp. 1 is less than the 25. It
overwrites the 25.[4, 10, 25, 25, 5] 10>1 then it overwrites again
Now, we have 4 elements in the sorted subarray. 5<25 then shift 25 to the right side and
pass
temp = 5 to the left side.
Now, we get the sorted array by simply putting the temp value.
PROCEDURE/CODE:
15
Name:- Pranav Ravindra Patil PRN:- 220105131328
print()
# Example usage
arr = [32, 31, 33, 25, 26]
print("Original array:", end=" ")
printArray(arr)
RESULT/OUTPUT:
16
Name:- Pranav Ravindra Patil PRN:- 220105131328
SOCSE, Sandip University, Nashik
EXPERIMENT 6
THEORY: The selection sort algorithm sorts an array by repeatedly finding the minimum
element (considering ascending order) from unsorted part and putting it at the beginning. The
algorithm maintains two subarrays in a given array.
1. The subarray which is already sorted.
2. Remaining subarray which is unsorted. In every iteration of selection sort, the
minimum element (considering ascending order) from the unsorted subarray is
picked and moved to the sorted subarray.
In this algorithm, we select the smallest element from an unsorted array in each pass and
swap with the beginning of the unsorted array. This process will continue until all the
elements are placed at right place. It is simple and an in-place comparison sorting algorithm.
1. The following are the steps to explain the working of the Selection sort in
Python. Let's take an unsorted array to apply the selection sort algorithm.
length = len(array) → 6
Step - 3: Now compare the minimum with the second element. If the second element is smaller
than the first, we assign it as a minimum.
Again we compare the second element to the third and if the third element is smaller than
second, assign it as minimum. This process goes on until we find the last element.
Step - 4: After each iteration, minimum element is swapped in front of the unsorted array.
Step - 5: The second to third steps are repeated until we get the sorted array.
1. Initial State: The list is divided into two parts: the sorted part (initially empty) and the
unsorted part (contains all elements).
2. Find Minimum: The algorithm scans the unsorted part of the list to find the minimum (or
maximum) element.
17
Name:- Pranav Ravindra Patil PRN:- 220105131328
3. Swap: Once the minimum (or maximum) element is found, it is swapped with the first element
of the unsorted portion.
4. Expand Sorted Part: The element that was swapped to the beginning of the unsorted portion
is now considered as part of the sorted portion.
5. Repeat: Steps 2-4 are repeated for the remaining unsorted portion, gradually expanding the
sorted portion and shrinking the unsorted portion.
6. Termination: The algorithm continues until the entire list is sorted, with the sorted portion
spanning the entire list and the unsorted portion becoming empty.
Selection Sort has a time complexity of O(n^2), where n is the number of elements in the list. This
makes it inefficient for large lists, and it's generally not recommended for large-scale sorting tasks.
However, it has the advantage of requiring only a small number of swaps, making it useful in
situations where minimizing the number of swaps is important (e.g., when writing data to flash
memory).
ALGORITHM:
1. selection_sort(array)
2. repeat (0, length - 1) times
3. set the first unsorted element as the minimum
4. for each of the unsorted elements
5. if element < currentMinimum
6. set element as new minimum
7. swap minimum with first unsorted position
8. end selection_sort
PROCEDURE/CODE:
18
Name:- Pranav Ravindra Patil PRN:- 220105131328
RESULT/OUTPUT:
19
Name:- Pranav Ravindra Patil PRN:- 220105131328
SOCSE, Sandip University, Nashik
EXPERIMENT 7
TITLE: Implement a Python Program to calculate the square root of a number by Newton's
Method
THEORY: Given an integer N and a tolerance level L, the task is to find the square root of
that number using Newton’s Method.
Examples:
Newton’s Method:
Let N be any number then the square root of N can be given by the formula:
● In the above formula, X is any assumed square root of N and root is the
correct square root of N.
● Tolerance limit is the maximum difference between X and root allowed.
20
Name:- Pranav Ravindra Patil PRN:- 220105131328
return root
# Driver code
if name == " main ":
n = 468
l = 0.00001
RESULT/OUTPUT:
21
Name:- Pranav Ravindra Patil PRN:- 220105131328
SOCSE, Sandip University, Nashik
EXPERIMENT 8
THEORY: Matrix multiplication is a binary operation that uses a pair of matrices to produce
another matrix. The elements within the matrix are multiplied according to elementary
arithmetic.
In the multiplication of two matrices, the row elements of the first matrix are multiplied to the
column elements of the second matrix.
A = [[5, 4, 3]
[2, 4, 6]
[4, 7, 9]]
And,
B = [[3, 2, 4]
[4, 3, 6]
[2, 7, 5]]
C would be the addition of above given two matrices, i.e., C = A+B, and therefore C should be:
As we can see that the resulting matrix C, which is also known as matrix product, has the same
number of rows as the first matrix (A matrix) and the same number of columns as the second
matrix (B matrix). We also know this type of multiplication of matrices as dot product of
matrices.
Multiplication of two matrices
Now, we will write a Python program for the multiplication of two matrices where we perform
the multiplication as we have performed in the above-given example. We can use various
methods to write a Python program like this, but in this tutorial, we will only use the following
two methods:
22
Name:- Pranav Ravindra Patil PRN:- 220105131328
In both methods, we will write an example program to understand their implementation for
multiplying two matrices.
In this method, we are going to use nested for loop on two matrices and perform
multiplication on them and store multiplication result in the third matrix as the result value.
In this method, we will use nested list comprehension to get the multiplication result of two
input matrices. While using the list comprehension method in the program, we will also use
'zip in Python' on the nested list.
PROCEDURE/CODE:
B =[
[9, 4, 7],
[5, 7, 2],
[1, 3, 9]
]
# Define an empty matrix to store the multiplication result
multiResult = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
# Using nested for loop method on A & B matrix
# Iterate through each row of matrix A
for m in range(len(A)):
# Iterate through each column of matrix B
for n in range(len(B[0])):
# Iterate through each element of matrix B's column
for o in range(len(B)):
# Calculate the product and accumulate it in the result matrix
multiResult[m][n] += A[m][o] * B[o][n]
23
Name:- Pranav Ravindra Patil PRN:- 220105131328
[3, 6, 8],
[4, 8, 3],
[6, 3, 7]
]
B = [
[9, 4, 7],
[5, 7, 2],
[1, 3, 9]
]
# Using nested list comprehension and zip in Python to calculate matrix
multiplication
multiResult = [
[sum(a * b for a, b in zip(Arow, Bcol)) for Bcol in zip(*B)]
for Arow in A
]
24
Name:- Pranav Ravindra Patil PRN:- 220105131328
RESULT/OUTPUT:
SOCSE, Sandip University, Nashik
USING NESTED FOR LOOP METHOD:
25
Name:- Pranav Ravindra Patil PRN:- 220105131458
SOCSE, Sandip University, Nashik
EXPERIMENT 9
TITLE: Implement a Python program to calculate the most frequent words in a text from a file.
THEORY: Data is often stored in text files, which is organized. There are many kinds of
files. Text files, music files, videos, and various word processor and presentation documents
are those we are familiar with.
Text files only contain characters whereas, all the other file formats include formatting
information that is specific to that file format. Operations performed on the data in files
include the read and write operations. To perform any operation the program must open the
file. The syntax to open a file is given below:
Though there are several ways of opening a file I prefer this way because we need not
specify the close statement at the end.
Reading a file:
There are several techniques for reading files. One way is reading the overall contents of the
file into a string and we also have iterative techniques in which in each iteration one line of
text is read. We, can also read each line of text and store them all in a list. The syntax for
each technique is given below
contents = f.read()
lines = f.readlines()
for line in f:
print(len(line))
26
Name:- Pranav Ravindra Patil PRN:- 220105131328
As our job is to just read the contents of the file and then finding the most frequent word in a
text read from a file we have no space for the write operation. In case you want to learn it go
through this link text file in Python
finding the most frequent words from a text read from a file.
First, you have to create a text file and save the text file in the same directory where you will
save your python program. Because once you specify the file name for opening it the
interpreter searches the file in the same directory of the program. Make sure you have
created and saved the file in proper directory.
The algorithm we are going to follow is quite simple first we open the file then we read the
contents we will see how many times each word is repeated and store them in a variable
called count. Then we check it with the maximum count which is initialized as zero in the
beginning. If count is less than maximum count we ignore the word if it is equal we will
place it in a list. Otherwise, if it is greater then we clear the list and place this word in the
list.
with open(fname,'r') as f:
we have opened the file as f and we will be using f whenever we have to specify the file.
Now we have to read the contents. We have many techniques for that as we have
previously discussed. But, the thing is that we should take the most reliable one for our task.
As we are concerned with the words of the file, it would be better if we read the entire
contents. And, then we split the string into a list with the words in the string using split
method.
Reading contents:
with open(fname,'r') as f:
contents=f.read()
words=content.split()
Now, we have all the words in a list we will implement the algorithm discussed early
27
Name:- Pranav Ravindra Patil PRN:- 220105131328
count = 0;
word = "";
maxCount = 0;
words = [];
#If maxCount is less than count then store value of count in maxCount
#and corresponding word to variable word
if(count > maxCount):
maxCount = count;
word = words[i];
28
Name:- Pranav Ravindra Patil PRN:- 220105131328
data.txt (note: this file is used for both above and below program)
What is Python? Python is a high-level, general-purpose, and very popular programming language.
Python programming language (latest Python 3) is being used in web development, Machine Learning
applications, along with all cutting-edge technology in Software Industry.
Python language is being used by almost all tech-giant companies like – Google, Amazon, Facebook,
Instagram, Dropbox, Uber… etc. The biggest strength of Python is huge collection of standard library
which can be used for the following: Machine Learning GUI Applications (like Kivy, Tkinter, PyQt etc. )
Web frameworks like Django (used by YouTube, Instagram, Dropbox) Image processing (like OpenCV,
Pillow) Web scraping (like Scrapy, BeautifulSoup, Selenium) Test frameworks Multimedia Scientific
computing Text processing and many more. Python Data Types Data types are the classification or
categorization of data items. It represents the kind of value that tells what operations can be performed on
a particular data. Since everything is an object in Python programming, data types are actually classes and
variables are instances (object) of these classes. The following are the standard or built-in data types in
Python: Numeric Sequence Type Boolean Set Dictionary Binary Types python else else else for python
python else mode mode
29
Name:- Pranav Ravindra Patil PRN:- 220105131328
30
Name:- Pranav Ravindra Patil PRN:- 220105131328
EXPERIMENT 10
Python3. 1. In the method overloading, methods or functions must have the same name and
different signatures. Whereas in the method overriding, methods or functions must have the
same name and same signatures.
But Python does not support function overloading. An error gets thrown if we implement
the function overloading code the way we do in other languages. The reason is as Python
does not have a data type for method parameters.
is polymorphism in Python?
For example, the + operator will perform arithmetic addition on two numbers, merge two lists,
or concatenate two strings. This feature in Python that allows the same operator to have
different meaning according to the context is called operator overloading.
Overriding occurs when the method signature is the same in the superclass and the child
class. Overloading occurs when two or more methods in the same class have the same name
but different parameters.
31
Name:- Pranav Ravindra Patil PRN:- 220105131328
Code:
Output:
def overloaded_function(*args):
if len(args) == 1:
print(f"This is a function with 1 argument: {args[0]}")
elif len(args) == 2:
32
Name:- Pranav Ravindra Patil PRN:- 220105131328
In the above code, we have defined two product method, but we can only use the second
product method, as python does not support method overloading. We may define many
methods of the same name and different arguments, but we can only use the latest defined
method. Calling the other method will produce an error. Like here calling will produce an
error as the latest defined product method takes three arguments
Output:
33
Name:- Pranav Ravindra Patil PRN:- 220105131328
EXPERIMENT 11
TITLE: Implement concept of class, instances and inheritance
Theoretical Overview:
● Class: A class is a blueprint or template for creating objects. It defines the attributes
(data) and methods (functions) that the objects of that class will have.
● Object/Instance: An object is an instance of a class. It is a concrete realization of the
class, with its own unique data and state.
2. Instances:
3. Inheritance:
Practical Implementation:
Let's implement the concepts of class, instances, and inheritance with a practical example:
34
Name:- Pranav Ravindra Patil PRN:- 220105131328
35
Name:- Pranav Ravindra Patil PRN:- 220105131328
OUTPUT
This practical implementation demonstrates the core concepts of classes, instances, and
inheritance. It showcases how classes can be structured, how instances are created from those
classes, and how subclasses can inherit and modify attributes and methods from their parent
class.
36
Name:- Pranav Ravindra Patil PRN:- 220105131328
def area(self):
pass # Placeholder for calculating area
Output:-
37
Name:- Pranav Ravindra Patil PRN:- 220105131328
EXPERIMENT 12
Theory: Python provides a wide range of internal libraries for basic operations like addition, and
external libraries for extended functionality like unit conversion.
• Internal Library (math): The math.fsum() function is used to perform addition, which
ensures better handling of floating-point numbers.
• External Library (pint): The pint library is used for unit conversion, enabling us to convert
the result of the addition from meters to centimeters.
This program performs the addition of two numbers using the internal math library and then
converts the result from meters to centimeters using the external pint library.
Algorithm:
1. Import Libraries:
• Import the internal math library for performing addition
• Import the external pint library for unit conversion.
3. Define Function:
• Define add_numbers(a, b) to perform the addition of two numbers using
math.fsum().
4. Input:
• Set the values for two numbers (in meters).
5. Calculate:
• Call add_numbers(a,b) to compute the sum.
6. Convert Units:
• Convert the result from meters to centimeters using pint.
7. Output:
• Display the sum in meters and centimeters
38
Name:- Pranav Ravindra Patil PRN:- 220105131328
PROCEDURE/CODE:
# Perform addition
sum_result = add_numbers(num1, num2)
OUTPUT:-
39