Lab Program Python Prathamesh
Lab Program Python Prathamesh
Ensure that you are aware of the test and its procedure before each
lab class. You will NOT be allowed to attend the class if you are
not prepared!
assigned to you.
Allaccidentsmustbereportedtoyourinstructororlaboratorysupervisor.
Thesurroundingsneartheequipmentmustbecleanedbeforeleaving
Laboratory report
ACADEMIC YEAR
PROGRAMME
PRN.NO
CERTIFICTAE
THEORY: Greatest Common Divisor (GCD) is a mathematical term to find the greatest
common factor that can perfectly divide the two numbers. A GCD is also known as the
Highest Common Factor (HCF). For example, the HCF/ GCD of two numbers 54 and 24 is 6.
Because 6 is the largest common divisor that completely divides 54 and 24.
In python, a gcd() is an inbuilt function offered by the math module to find the greatest
Syntax: gcd(a, b)
Where a and b are the two integer number passes as an argument to the function gcd().
Let's create a program to print the GCD of two number using the inbuilt function of math.gcd()
in python.
# create a program to print the gcd of two number in python using the math.gcd() function.
import math
print(" GCD of two number -24 and -18 is ", math.gcd(-24, -18))
RESULT / OUTPUT:
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.
PROCEDURE / CODE:
RESULT/OUTPUT:
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.
Step - 2: If element is found, return the index position of the key.
1. LinearSearch(list, key)
2. for each item in the list
3. if item == value
4. return its index position
5. return -1
Page 11 of 54
PROGRAM / CODE:
if result == -1:
print("Element not found")
else:
print(f"Element found at index: {result}")
RESULT/OUTPUT:
Explanation:
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)
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.
# Initial list1
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 45
# 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")
# Test list1ay
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 32
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.
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.
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]
[10, 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.
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:
# Example usage
arr = [12, 11, 13, 5, 6]
print("Original array:", end=" ")
printArray(arr)
RESULT/OUTPUT:
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
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.
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:
# Input array
arr = [-2, 45, 0, 11, -9, 88, -97, -202, 747]
size = len(arr)
RESULT/OUTPUT:
SOCSE, Sandip University, Nashik
EXPERIMENT 7
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.
return root
# Driver code
if name == " main ":
n = 378
l = 0.00001
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:
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 = [
[3, 2, 4],
[4, 3, 6],
[2, 7, 5]
]
B = [
[3, 2, 4],
[4, 3, 6],
[2, 7, 5]
]
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))
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()
Finding the most frequent word:
Now, we have all the words in a list we will implement the algorithm discussed early
Page 33 of 54
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];
Now, we have the most frequent words in the list ‘l’ that will be printed at last.
Output:
Word Count:
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
from collections import Counter
OUTPUT:
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.
SOCS
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.
Code:
def overloaded_function(*args):
if len(args) == 1:
print(f"This is a function with 1 argument: {args[0]}")
elif len(args) == 2:
print(f"This is a function with 2 arguments: {args[0]},
{args[1]}")
elif len(args) == 3:
print(f"This is a function with 3 arguments: {args[0]},
{args[1]}, {args[2]}")
else:
print("Invalid number of arguments")
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:
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:
1. We define a base class Shape with an attribute color and a method area (with a
placeholder implementation).
2. We define two subclasses, Circle and Rectangle, that inherit from the Shape class.
Each subclass has its own attributes (radius for Circle, and width and height for
Rectangle), and overrides the area method with specific implementations.
3. We create instances (circle_instance and rectangle_instance) of the subclasses
by providing specific attribute values.
4. We call the area method on the instances to calculate and print their respective areas
based on the overridden implementations.
5. # Define a base class called 'Animal'
6. class Animal:
7. def init (self, name, species):
8. self.name = name
9. self.species = species
10.
11. def make_sound(self):
12. pass # This method will be overridden by subclasses
13.
14. def introduce(self):
15. print(f"I am a {self.species} named {self.name}.")
16.
17. # Define a subclass 'Dog' that inherits from 'Animal'
18. class Dog(Animal):
19. def init (self, name, breed):
20. super(). init (name, species="Dog") # Call parent
class constructor using 'super()'
21. self.breed = breed
22.
23. def make_sound(self):
24. return "Woof!" # Override the 'make_sound' method
25.
26. def introduce(self): # Override the 'introduce' method
27. print(f"I am a {self.breed} dog named {self.name}.")
28.
29. # Define another subclass 'Cat' that inherits from 'Animal'
30. class Cat(Animal):
31. def init (self, name, color):
32. super(). init (name, species="Cat") # Call parent
class constructor using 'super()'
33. self.color = color
34.
35. def make_sound(self):
36. return "Meow!" # Override the 'make_sound' method
37.
38. def introduce(self): # Override the 'introduce' method
39. print(f"I am a {self.color} cat named {self.name}.")
40.
41. # Create instances of the subclasses
42. dog_instance = Dog("Buddy", "Golden Retriever")
43. cat_instance = Cat("Whiskers", "Gray")
44.
45. # Call methods on the instances
46. dog_instance.introduce() # Calls the 'introduce'
method of the 'Dog' class
47. print(dog_instance.make_sound()) # Calls the 'make_sound'
method of the 'Dog' class
48.
49. cat_instance.introduce() # Calls the 'introduce'
method of the 'Cat' class
50. print(cat_instance.make_sound()) # Calls the 'make_sound'
method of the 'Cat' class
OUTPUT
def area(self):
pass # Placeholder for calculating area