Python Lab Manual
Python Lab Manual
EXPERIMENT 1
greatest common factor that can perfectly divide the two numbers. A GCD
Highest Common Factor (HCF). For example, the HCF/ GCD of two numbers 54
and 24.
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.
RESULT / OUTPUT:
Explanation
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
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
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.
17YCS514-Python Programming Laboratory
PROCEDURE / CODE:
RESULT/OUTPUT:
Conclusion:
This program demonstrates a simple algorithm for finding the largest element in an array. By
initializing with the first element and then iterating through the array to compare each
subsequent element, the program efficiently determines the maximum value. The key
operations are the initialization of the comparison variable (max_element), the iteration
through the array, and the conditional update based on comparisons. This approach ensures
that the program runs in linear time, O(n), where n is the number of elements in the array,
making it both straightforward and efficient for finding the maximum value.
17YCS514-Python Programming Laboratory
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.
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.
1. LinearSearch(list, key)
2. for each item in the list
3. if item == value
4. return its index position
5. return -1
PROGRAM / CODE:
17YCS514-Python Programming Laboratory
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.
17YCS514-Python Programming Laboratory
EXPERIMENT 4
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
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.
PROCEDURE/CODE:
FOR ITERATIVE BINARY SEARCH METHOD:
17YCS514-Python Programming Laboratory
Result/Output :
Explanation/Conclusion :
The binary search algorithm efficiently finds an element in a sorted list by continuously
narrowing down the search range by half. This method significantly reduces the number of
comparisons needed, making it much faster than a linear search, especially for large datasets,
with a time complexity of O(log n).
Result/Output :
Conclusion/Explanation :
This recursive binary search program efficiently locates an element in a sorted list by repeatedly
dividing the search interval in half. It checks the middle element, and if it matches the target, it
returns the index. If the target is smaller or larger, the function recursively searches the left or
right sublist, respectively. If the element is not found after all divisions, it returns `-1`. This
method is efficient, with a time complexity of O(log n), making it ideal for searching large sorted
datasets.
17YCS514-Python Programming Laboratory
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
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 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:
Explanation/Conclusion :
The insertion sort algorithm sorts an array by building a sorted section from left to right.
It repeatedly takes the next element and inserts it into its correct position within the
sorted part of the array, shifting larger elements to the right as needed. This method is
simple and efficient for small or nearly sorted arrays, with a time complexity of O(n²) in
the worst case. The algorithm is stable and performs well for datasets that are already
partially sorted.
17YCS514-Python Programming Laboratory
17YCS514-Python Programming Laboratory
Result/Output :
17YCS514-Python Programming Laboratory
EXPERIMENT 6
TITLE: Implement a Python Program to perform selection sort
THEORY: The selection sort algorithm sorts an array by repeatedly finding the
minimum element (considering ascending order) from unsorted part and
putting it at thebeginning. 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.
sort algorithm.
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.
17YCS514-Python Programming Laboratory
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
2. Here's how the Selection Sort algorithm works step by step:
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
9.
Explanation/Conclusion :
The selection sort algorithm sorts an array by repeatedly finding the smallest (or largest)
element from the unsorted portion and moving it to the sorted portion. It involves selecting the
minimum element and swapping it with the first unsorted element in each iteration. This
process continues until the entire array is sorted. While simple and easy to implement,
selection sort has a time complexity of O(n²), making it less efficient for large datasets
17YCS514-Python Programming Laboratory
PROCEDURE/CODE :
Result/Output :
17YCS514-Python Programming Laboratory
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:
Input: N = 16, L = 0.0001
Output: 4
42 = 16
Input: N = 327, L = 0.00001
Output: 18.0831
Newton’s Method:
Let N be any number then the square root of N can be given by the
formula: root = 0.5 * (X + (N / X)) where X is any guess which can be
assumed to be N or 1.
● 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.
PROCEDURE/CODE :
17YCS514-Python Programming Laboratory
Result/Output :
17YCS514-Python Programming Laboratory
EXPERIMENT 8
matrices: 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: C = [[37, 43, 59]
[34, 58, 62]
[58, 92, 103]]
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:
PROCEDURE/CODE:
USING NESTED FOR LOOP METHOD:
17YCS514-Python Programming Laboratory
Result/Output :
Result/Output.
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
17YCS514-Python Programming Laboratory
must open the file. The syntax to open a file is given below:
«block»
Though there are several ways of opening a file I prefer this way because we need
not specify the close statement at the end.
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
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.
17YCS514-Python Programming Laboratory
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
17YCS514-Python Programming Laboratory
count =
0; word
= "";
maxCount
= 0;
words =
[];
for s in
string:
words.appen
d(s);
count = 1;
#Count each word in the file and store it in variable
Now, we have the most frequent words in the list ‘l’ that will be printed at last.
Output: