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

Lab Program Python Prathamesh

jtyddtgj

Uploaded by

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

Lab Program Python Prathamesh

jtyddtgj

Uploaded by

S K Edition
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Laboratory Manual

School of Computer Science


Name of the School:
and Engineering
Name of the Department: Computer Science and engineering

Name of the Programme: Python Programming

Name Of Faculty Mr. Aaditya

Qualification PHD (Computer Science Engineering)


Professor
Designation
Class: TE (Third Year) CSE

Course/ Course Code: 17YCS512

Academic Year: 2024-25


Guidelines
Laboratory rules

Attendance is required for all lab classes. Students who do not


attend lab will not receive credit.

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!

Personal safety is top priority. Do not use equipment that is not

assigned to you.

Allaccidentsmustbereportedtoyourinstructororlaboratorysupervisor.

Thesurroundingsneartheequipmentmustbecleanedbeforeleaving

eachlab class. Ensure that readings are checked and marked by

your TA for each lab period.

Laboratory report

1. Each student has to submit the report for each experiment.


2. Your report is to be written only in the space provided in the manual
3. Please write your number and, batch and group number.
4. Your report must be neat, well organized, and make a
professional impact. Label all axes and include proper units.
5. Your reports should be submitted within 7 days and before the
beginning of the lab class of the next batch.
6. Your reports will be as per rubrics provided at the end of each experiment
7. Anyone caught plagiarizing work in the laboratory report, from a
current or past student's notebook, will receive 0 on the grading scale.
NAME OF STUDENT

ACADEMIC YEAR

PROGRAMME

CLASS / DIV /ROLL.NO

PRN.NO
CERTIFICTAE

This is to certify that


Mr./Miss…………………………….………………………………………………………….
Roll no………………….... PRN No………………………………………….
of class…………...…………. has satisfactorily/unsatisfactorily
completed the Term Work of Course ……………………………
in this School during academic year …………………………….
Table of contents
S.No Title of Experiment Date of Remarks
Conducti
on
1 Implement a Python program to
Calculate GCD of two numbers.
2 Implement a Python Program to
calculate the square root of a
number by Newton's Method.
3 Implement a Python Program to find
the largest number from a list of
numbers.
4 Implement a Python Program to
perform Liner search
5 Implement a Python Program to
perform Binary search
6 Implement a Python Program to
perform insertion sort.
7 Implement a Python Program to
perform selection sort.
8 Implement a Python program to
multiply matrices.
9 Implement a Python program to
calculate the most frequent words in
a text from a file.
10 Implement function overloading with
different function signatures.
11 Implement concept of class, instances
and inheritance.
12 Implement internal and external
library.
13 Solve algorithmic problems by
program using different problem-
solving strategies.
14 Search content using regular
expression library in python.
15 Implement Matrix multiplication
using multi-threading in python.
16 Perform Linux administration task
using python

Course Teacher Head of Department Dean Academics


EXPERIMENT 1:

TITLE: Implement a Python program to Calculate GCD of two numbers.

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.

GCD Using gcd() Function

In python, a gcd() is an inbuilt function offered by the math module to find the greatest

common divisor of two numbers.

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.

PROCEDURE / ALGORITHM / CODE:

# create a program to print the gcd of two number in python using the math.gcd() function.

import math

print(" GCD of two number 0 and 0 is ", math.gcd(0, 0))

#math.gcd(a, b), a and b are the two integer number

print(" GCD of two number 0 and 48 is ", math.gcd(0, 48))

a = 60 # assign the number to variable a

b = 48 # assign the number to variable b

print(" GCD of two number 60 and 48 is ", math.gcd(a, b))

# pass the variable a and b to math.gcd() function.


print(" GCD of two number 48 and -12 is ", math.gcd(48, -12))
# pass the integer number

print(" GCD of two number -24 and -18 is ", math.gcd(-24, -18))

print(" GCD of two number -60 and 48 is ", math.gcd(-60, 48))

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 1: Declare and initialize an array.

● STEP 2: Store first element in variable max.

● 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:

arr = [25, 11, 7, 75, 56]

# Initialize max with the first element of the array


max = arr[0]

# Loop through the array


for i in range(1, len(arr)):
# Compare elements of the array with max
if arr[i] > max:
max = arr[i]

print("Largest element present in the given array: " + str(max))

RESULT/OUTPUT:
EXPERIMENT 3

TITLE: Implement a Python Program to perform Linear search.

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.

There are two types of searching -

● Linear Search
● Binary Search

Both techniques are widely used to search an element in the given list.

What is a Linear Search

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.

Concept of Linear Search

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.

Step - 3: If element is not found, return element is not present.

Linear Search Algorithm


There is list of n elements and key value to be searched.
Below is the linear search algorithm.

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:

def linear_search(arr, key):


for i in range(len(arr)):
if arr[i] == key:
return i
return -1

# Taking user input for the list and the key


input_list = input("Enter a list of numbers separated by spaces:
").split()
key = int(input("Enter the key to search: ")) # Convert key to an
integer

# Converting the input_list elements to integers


int_list = [int(x) for x in input_list]

result = linear_search(int_list, key)

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.
EXPERIMENT 4

TITLE: Implement a Python Program to perform Binary search

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.

Let's have a step by step implementation of binary search.

We have a sorted list of elements, and we are looking for the index position of 45.

[12, 24, 32, 39, 45, 50, 54]

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.

Next, we calculate the value of the middle element in the array.

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.

Repeat until the number that we are searching for is found.


PROCEDURE/CODE:

FOR ITERATIVE BINARY SEARCH METHOD:


# Iterative Binary Search Function
def binary_search(list1, n):
low = 0
high = len(list1) - 1

while low <= high:


mid = (high + low) // 2 # Calculate the middle index

# Check if n is present at mid


if list1[mid] == n:
return mid # Element found, return its index
elif list1[mid] < n:
low = mid + 1 # If n is greater, search in the right halfLAB MANUA
else:
high = mid - 1 # If n is smaller, search in the left half

return -1 # Element was not present in the list

# 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")

RECURSIVE BINARY SEARCH:


# Python program for recursive binary search.
# Returns index position of n in list1 if present, otherwise -1
def binary_search(list1, low, high, n):
# Check base case for the recursive function
if low <= high:
mid = (low + high) // 2

# If element is available at the middle itself then return its index


if list1[mid] == n:
return mid
# If the element is smaller than mid value, then search moves
# left sublist1
elif list1[mid] > n:
return binary_search(list1, low, mid - 1, n)
# Else the search moves to the right sublist1
else:
return binary_search(list1, mid + 1, high, n)
else:
# Element is not available in the list1
return -1

# Test list1ay
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 32

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") LAB MANUA L : PYTHON
RESULT/OUTPUT:

FOR ITERATIVE BINARY SEARCH METHOD

FOR RECURSIVE 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.
SOCSE, Sandip University, Nashik
EXPERIMENT 5

TITLE: Implement a Python Program to perform insertion sort

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.

Let's understand the following terms.

What is the meaning of in-place and stable?

● 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.

● Spilt a list in two parts - sorted and unsorted.


● Iterate from arr[1] to arr[n] over the given array.
● Compare the current element to the next element.
● If the current element is smaller than the next element, compare to the element
before, Move to the greater elements one position up to make space for the
swapped element.

Let's understand the following example.

We will consider the first element in the sorted array in the following array.

[10, 4, 25, 1, 5]

The first step to add 10 to the sorted subarray

[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.

[10, 10, 25, 1, 5] (temp = 4)

Here the 4 is lesser than all elements in sorted subarray, so we insert it at the first index
position.

[4, 10, 25, 1, 5]

We have two elements in the sorted subarray.


SOCSE, Sandip University, Nashik
Now check the number 25. We have saved it into the temp variable. 25> 10 and
also 25> 4then we put it in the third position and add it to the sorted sub array.

[4, 10, 25, 1, 5]

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

[4, 25, 10, 25, 5]

[25, 4, 10, 25, 5] 4>1 now put the value of temp = 1

[1, 4, 10, 25, 5]

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.

[1, 4, 10, 25, 25] put temp = 5

Now, we get the sorted array by simply putting the temp value.

[1, 4, 5, 10, 25]

The given array is sorted.

PROCEDURE/CODE:

# Function to perform insertion sort


def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
# Compare key with elements of the sorted subarray on the left
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j] # Shift elements to the right if
greater than key
j -= 1
arr[j + 1] = key # Place key in the correct position

# Function to print elements of an array


def printArray(arr):
for element in arr:
print(element, end=" ")
print()

# Example usage
arr = [12, 11, 13, 5, 6]
print("Original array:", end=" ")
printArray(arr)

insertionSort(arr) # Sort the array using insertion sort


print("Sorted array:", end=" ")
printArray(arr)

RESULT/OUTPUT:
SOCSE, Sandip University, Nashik
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
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.

Working of Selection Sort

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.

[30, 10, 12, 8, 15, 1]

Step - 1: Get the length of the array.

length = len(array) → 6

Step - 2: First, we set the first element as minimum element.

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.

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

PROCEDURE/CODE:

# Selection sort in Python

# Time complexity: O(n*n)

# Function to perform selection sort


def selectionSort(array, size):
# Loop through each element in the array
for ind in range(size):
min_index = ind # Assume the current index has the minimum value

# Loop through the remaining unsorted portion of the array


for j in range(ind + 1, size):
# Find the index of the minimum element in the remaining array
if array[j] < array[min_index]:
min_index = j

# Swap the minimum element with the current element


(array[ind], array[min_index]) = (array[min_index], array[ind])

# Input array
arr = [-2, 45, 0, 11, -9, 88, -97, -202, 747]
size = len(arr)

# Call the selectionSort function to sort the array


selectionSort(arr, size)

# Display the sorted array


print('The array after sorting in Ascending Order by selection sort is:')
print(arr)

RESULT/OUTPUT:
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:

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.

Approach: The following steps can be followed to compute the answer:

1. Assign X to the N itself.


2. Now, start a loop and keep calculating the root which will surely move
towards the correct square root of N.
3. Check for the difference between the assumed X and calculated root, if not
yet inside tolerance then update root and continue.
4. If the calculated root comes inside the tolerance allowed then break out of
the loop.
5. Print the root.
SOCSE, Sandip University, Nashik
PROCEDURE/CODE:

# Python3 implementation of the approach

# Function to return the square root of a number using Newton's method


def squareRoot(n, l):
# Assuming the sqrt of n as n only
x = n

# To count the number of iterations


count = 0

# Iterate using a loop


while True:
count += 1

# Calculate a more closed x


root = 0.5 * (x + (n / x))

# Check for closeness using the provided tolerance 'l'


if abs(root - x) < l:
break

# Update root for the next iteration


x = root

return root

# Driver code
if name == " main ":
n = 378
l = 0.00001

# Call the squareRoot function and print the result


print("Square root of", n, ":", squareRoot(n, l))
RESULT/OUTPUT:
SOCSE, Sandip University, Nashik
EXPERIMENT 8

TITLE: Implement a Python program to multiply matrices

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.

Example: Suppose we have given following two A and B 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:

1. Using nested for loop method


2. Using nested list comprehension method
In both methods, we will write an example program to understand their implementation for
multiplying two matrices.

Method 1: Using nested for loop method:

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.

Method 2: Using nested list comprehension method:

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:

1. USING NESTED FOR LOOP METHOD:

# 1. USING NESTED FOR LOOP METHOD:


# Define two matrices A & B
A = [
[5, 4, 3],
[2, 4, 6],
[4, 7, 9]
]

B = [
[3, 2, 4],
[4, 3, 6],
[2, 7, 5]
]

# 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]
# Printing multiplication result
print("The multiplication result of matrix A and B is:")
for res in multiResult:
print(res)

2. USING NESTED LIST COMPREHENSION METHOD:

# 2. USING NESTED LIST COMPREHENSION METHOD:


# Define two matrices A & B
A = [
[5, 4, 3],
[2, 4, 6],
[4, 7, 9]
]

B = [
[3, 2, 4],
[4, 3, 6],
[2, 7, 5]
]

# 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
]

# Printing multiplication result


print("The multiplication result of matrix A and B is:")
for res in multiResult:
print(res)
RESULT/OUTPUT:
SOCSE, Sandip University, Nashik
USING NESTED FOR LOOP METHOD:

USING NESTED LIST COMPREHENSION METHOD:


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:

with open(«filename», «mode») as «variable»:


«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.

For more understanding on files go through this link handling files

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

#to read the entire contents of text into a single string

with open('file1.txt', 'r') as f:

contents = f.read()

#to read each line and store them as list

with open('file1.txt', 'r') as f:

lines = f.readlines()

#for iterative method of reading text in files

with open('planets.txt', 'r') as f:

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.

Let us start with initializing variables and opening file

fname=input("enter file name")

count=0 #count of a specific word

maxcount=0 #maximum among the count of each words

l=[] #list to store the words with maximum count

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 = [];

#Opens a file in read mode


file = open("/content/data.txt", "r")

#Gets each line till end of file is reached


for line in file:
#Splits each line into words
string = line.lower().replace(',','').replace('.','').split(" ");
#Adding all words generated in previous step into words
for s in string:
words.append(s);

#Determine the most repeated word in a file


for i in range(0, len(words)):
count = 1;
#Count each word in the file and store it in variable count
for j in range(i+1, len(words)):
if(words[i] == words[j]):
count = count + 1;

#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];

print("Most repeated word: " + word);


file.close();

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

# Create a Counter object to count word frequencies


word_counter = Counter()

# Opens a file in read mode


with open("/content/py_data.txt", "r") as file:
# Gets each line till the end of the file is reached for
line in file:
# Splits each line into words
words = line.lower().replace(',', '').replace('.', '').split() #
Update the word_counter with the words from the current line
word_counter.update(words)

# Determine the most frequent words


most_common_words = word_counter.most_common(10) # Change 10 to the
number of top words you want to display

# Print the most frequent words and their counts print("Most


frequent words:")
for word, count in most_common_words:
print(f"{word}: {count}")

OUTPUT:
EXPERIMENT 10

TITLE: Implement a Python program to Implement function overloading with


different function signatures
THEORY: Python does not support function overloading. When we define multiple functions
with the same name, the later one always overrides the prior and thus, in the namespace,
there will always be a single entry against each function name.

What is function overloading and overriding in Python?

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.

Why does Python not overload?

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

Does Python support overriding?

Method overriding is an ability of any object-oriented programming language that allows a


subclass or child class to provide a specific implementation of a method that is already
provided by one of its super-classes or parent classes.

What is polymorphism in Python?

The literal meaning of polymorphism is the condition of occurrence in different forms.


Polymorphism is a very important concept in programming. It refers to the use of a single
type entity (method, operator or object) to represent different types in different scenarios.

What is overloading in Python with example?

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.

What is difference between method overriding and 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.

What are basic overloading methods in Python?

What is method overloading in Python?


● Methods in Python can be called with zero, one, or more parameters.
● Overloading is a method or operator that can do different
functionalities with the same name.
● In the code above, we are able to call the method Hello in two different
ways with the help of method overloading .

Is constructor overloading possible in Python?

Python does not support Constructor overloading; it has no form of function. In


Python, Methods are defined solely by their name, and there can be only one
method per class with a given name.

What is function overloading explain?

An overloaded function is really just a set of different functions that happen to


have the same name. The determination of which function to use for a particular
call is resolved at compile time. In Java, function overloading is also known as
compile-time polymorphism and static polymorphism.

Code:

# A single product method that can handle different numbers of


arguments
def product(*args):
if len(args) == 2:
p = args[0] * args[1]
print(p)
elif len(args) == 3:
p = args[0] * args[1] * args[2]
print(p)
else:
print("Invalid number of arguments")

# Uncommenting the below line will now work correctly


product(4, 5)

# This line will call the second product method


product(4, 5, 5)

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")

# Call the overloaded function with different signatures


overloaded_function(10) # Calls the function with 1
argument: 10
overloaded_function(20, 30) # Calls the function with 2
arguments: 20, 30
overloaded_function(40, 50, 60) # Calls the function with 3
arguments: 40, 50, 60
overloaded_function(70, 80, 90, 100) # Calls the function with more
than 3 arguments, prints "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:

1. Classes and Objects:

● 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:

● An instance is a specific object created from a class.


● Each instance has its own set of attribute values, which can be different from other
instances of the same class.
● Instances can call and interact with the methods defined in their class.

3. Inheritance:

● Inheritance is a mechanism that allows a new class (subclass/derived class) to inherit


attributes and methods from an existing class (superclass/base class/parent class).
● Subclasses can add or override methods and attributes inherited from the superclass.
● Inheritance promotes code reuse and helps establish a hierarchical relationship
between classes.

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

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.
2.Instances:

# Define a base class 'Shape'


class Shape:
def init (self, color):
self.color = color

def area(self):
pass # Placeholder for calculating area

# Define a subclass 'Circle' that inherits from 'Shape'


class Circle(Shape):
def init (self, color, radius):
super(). init (color)
self.radius = radius

def area(self): # Override the 'area' method


return 3.14159 * self.radius ** 2

# Define another subclass 'Rectangle' that inherits from 'Shape'


class Rectangle(Shape):
def init (self, color, width, height):
super(). init (color)
self.width = width
self.height = height

def area(self): # Override the 'area' method


return self.width * self.height

# Create instances of the subclasses


circle_instance = Circle("Red", 5)
rectangle_instance = Rectangle("Blue", 4, 6)

# Call methods on the instances


print(f"Circle Area: {circle_instance.area()}")
print(f"Rectangle Area: {rectangle_instance.area()}")
OUTPUT:

You might also like