AI&DS PYTHON Lab Record
AI&DS PYTHON Lab Record
COIMBATORE - 641107
REGULATION 2024
Academic Year: 2024-
2025 Year/Semester:
I/01
1
BONAFIDE CERTIFICATE
Engineering
Place:
Date :
2
Internal Examiner External Examiner
3
INDEX
Page
Date Experiment Name Mark Signature
Number
4
2(b) Circulate ‘n’ values
5
Basic Operations (Insertion, Updating, deletion,
5(a)
accessing)
6(a) Membership
6(b) Operations
6(c) Modifications
7 Operations of Dictionaries
6
8(a) Factorial
9(a) Reverse
9(b) Palindrome
7
Implementing real-time/technical applications
11
using file handling
8
Exp No.1 Identification and solving of simple real life or scientific or technical
problems, and developing flow charts for the same. (Electricity Billing, Retail
shop billing, Sin series, weight of a motorbike, Weight of a steel bar, compute
Electrical Current in Three Phase AC Circuit, etc.)
Calculation AIM:
To draw the flowchart for electricity bill calculation with the following rates for its
customers: -
Draw a flowchart to calculated the net amount of the bill for each consumer and print it.
ALGORITHM:
Step 1: Start
Step 3: Check
1<=unit<=200
9
Step 5: Check unit>500
Step 7: Stop
FLOWCHART:
10
Exp No: 1) b. Flowchart for retail shop bill
calculation AIM:
ALGORITHM:
Step 1: Start
Step 4: Read No of
Quantity
11
FLOWCHART:
12
Exp No: 1) c. Flowchart for computing sin series
AIM:
ALGORITHM:
Step 1: Take in the value of x in degrees and the number of terms and store it in separate
variables.
Step 3: Define a sine function and using a for loop, first convert degrees to radians.
Step 4: Then use the sine formula expansion and add each term to the sum
Step 6: Stop
13
FLOWCHART:
14
Exp No: 1) d. Flowchart for calculating the weight of a motorbike
AIM:
ALGORITHM:
Step 1: Start
Step 2: Read
D,L
Step 4: Print w
Step 5:
Stop
FLOWCHART:
15
Exp No: 1) e. Flowchart for calculating the weight of a Steelbar
AIM:
ALGORITHM:
Step 1: Start
Step 2: Read LBS
Step 3: Compute w=LBS/2.2046
Step 4: Print w
Step 5: Stop
FLOWCHART:
16
Exp No : 1) f. Flowchart for calculating the compute Electrical Current in Three Phase
AC Circuit
AIM :
ALGORITHM :
Step 1: Start
Step 2: Read kva,voltage
Step 3: Compute current=kva/voltage
Step 4: Print current
Step 5: Stop
FLOWCHART:
RESULT:
Thus the flow charts were successfully drawn the above concept of (Electricity Billing,
Retail shop billing, Sin series, weight of a motorbike, Weight of a steel bar, compute
Electrical Current in Three Phase AC Circuit, etc.)
17
Exp No. 2 PYTHON PROGRAMS USING SIMPLE STATEMENTS AND
EXPRESSIONS
AIM:
To write python programs using simple statements and expressions. These Python
programs perform basic tasks like calculating the sum of two numbers, checking if a number is
even or odd, computing the area of a circle using πr², finding the largest of three numbers, and
reversing a string. They demonstrate essential operations like arithmetic, conditional checks, and
string manipulation.
variables ALGORITHM:
18
OUTPUT:
ALGORITHM:
STEP 5: Stop
PROGRAM:
list=[10,20,30,40,50]
n=2 print(list[n:]
+list[:n])
OUTPUT:
19
2 (c) Distance between two points
ALGORITHM:
PROGRAM:
import math
p1 = [4, 0]
p2 = [6, 6]
) print(distance)
OUTPUT:
6.324555320336759
RESULT:
Thus, the program for simple python statements and expressions were executed
and the output is verified.
20
Exp No :3
AIM:
To write a python program to evaluate 12+22+32+…+N2.
ALGORITHM:
Step 1: User must first enter the value and store it in a variable.
Step 2: The while loop is used and the last digit of the number is obtained by using the
modulus operator.
Step 3: The digit is added to another variable each time the loop is executed.
Step 4: Stop
PROGRAM
OUTPUT:
Enter a number:
10 Sum=385
21
3 (b ) Number Pattern
ALGORITHM:
STEP 4: Stop
PROGRAM:
for j in range(0, n-
C=1
C = C * (i - j) // j
print()
22
OUTPUT:
11
121
1331
14641
ALGORITHM:
STEP 3: Stop
PROGRAM:
num_rows = int(input("Enter the number of rows"));
print(end=" ")
print()
23
OUTPUT:
**
***
****
*****
RESULT:
Thus, the program using conditionals and loops has been executed and verified.
24
Exp No: 4
IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING LISTS
AIM:
To perform insertion, updating, deletion, accessing elements, and list
comprehensions. Implement linear search and binary search on a list. Add two matrices using
nested lists. Implement sorting algorithms using lists.
ALGORITHM:
1. Define the Problem Clearly state the objective, such as sorting a list,
searching an element, or performing matrix operations.
2. Input the Data Accept inputs from the user or define them directly in the code, like
lists, numbers, or matrices.
3. Initialize Variables Set up necessary variables, such as counters,
accumulators, or placeholders for results.
4. Process the Data Use conditionals, loops, or functions to perform
operations like traversing, searching, or sorting.
5. Store or Update Results Collect the computed values into variables, lists, or
matrices as required.
6. Output the Results Display the final results using print statements or return
values for further use.
25
4 a) Basic Operations
1. insert
# Initialize an empty list a
= []
# Adding 10 to end of list
a.append(10)
print("After append(10):", a) #
Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)
# Adding multiple elements [15, 20, 25] at the end
a.extend([15, 20, 25])
print("After extend([15, 20, 25]):", a)
2. update
a = [10, 20, 30, 40, 50]
# Change the second element a[1]
= 25
print(a)
3. delete
a = [10, 20, 30, 40, 50]
# Removes the first occurrence of 30
a.remove(30)
print("After remove(30):", a)
# Removes the element at index 1 (20)
popped_val = a.pop(1)
print("Popped element:", popped_val)
print("After pop(1):", a)
26
# Deletes the first element (10)
del a[0]
print("After del a[0]:", a)
5. accessing
a = ['apple', 'banana', 'cherry']
# Accessing the first item
print(a[0])
# Accessing the second item
print(a[1])
# Accessing the third item
print(a[2])
b) LINEAR SEARCH
if (array[i] == x):
return i
return -1
x = 11
n = len(array)
27
result = linearSearch(array, n, x)
if(result == -1):
else:
OUTPUT
BINARY SEARCH
if array[mid] == x:
return mid
x:
low = mid + 1
else:
high = mid - 1
return -1
x = 22
28
result = binarySearch(array, x, 0, len(array)-1)
if result != -1:
29
print(str(result))
else:
print("Not found")
Output
matrix = []
a = []
range(Column):
a.append(int(input()))
matrix.append(a)
30
# For printing the
range(Row):
print()
OUTPUT
56
78
d) 1. MERGE SORT
n1 = m - l +
1 n2 = r - m
L = [0] * n1
R = [0] * n2
for i in range(n1):
31
L[i] = arr[l + i]
32
for j in range(n2):
R[j] = arr[m + 1 + j]
i=0
j=0
k=l
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
arr[k] = L[i]
i += 1
k += 1
arr[k] = R[j]
j += 1
k += 1
33
def merge_sort(arr, l, r):
if l < r:
m = l + (r - l) // 2
merge_sort(arr, l, m)
merge_sort(arr, m + 1, r)
merge(arr, l, m, r)
def print_array(arr):
for i in arr:
print()
arr_size = len(arr)
print_array(arr)
merge_sort(arr, 0, arr_size -
print_array(arr)
34
OUTPUT
Given array is
12 11 13 5 6 7
Sorted array
is 5 6 7 11 12
13
d. 2. INSERTION SORT
def insertion_sort(arr):
for i in range(1,
len(arr)): key =
arr[i]
j=i-1
arr[j + 1] = arr[j]
j=j-1
arr[j + 1] = key
def print_array(arr):
for i in arr:
print()
35
n = len(arr)
print_array(arr)
36
insertion_sort(arr) print("\
print_array(arr)
OUTPUT
Given array
is 12 11 13 5
6
Sorted array
is 5 6 11 12
13
d.3.BUBBLE SORT
def bubble_sort(arr):
for i in range(n):
swapped = True
37
print("Unsorted list is:")
print(arr)
bubble_sort(arr)
print(arr)
OUTPUT
RESULT:
The results of the programs are as follows: Basic list operations show successful
insertion, updating, deletion, and accessing with comprehensions producing squares. Linear
38
search finds an index, and binary search works after sorting. Matrix addition gives element-wise
sums. Bubble, insertion, and merge sort all produce a sorted list efficiently.
39
Exp No: 5
CREATE A TUPLE AND PERFORM ITS OPERATIONS FOR THE FOLLOWING:
c. Components of a car
AIM:
To perform insertion, updating, deletion, and accessing elements in a tuple, library operations
and material construction.
ALGORITHM:
40
a) Creating a Tuple
# Creating an empty
Tuple Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
# Creating a Tuple
# with the use of string
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple
with # the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
# Creating a Tuple
# with the use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)
OUTPUT
Initial empty Tuple:
()
Tuple with the use of
String: ('Geeks', 'For')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of
function: ('G', 'e', 'e', 'k', 's')
41
Inserting Tuple
test_list = [5, 6, 7]
test_list += test_tup
# printing result
OUTPUT
42
Accessing Tuple
# Accessing
Tuple # with
Indexing
print(Tuple1[0])
# Tuple unpacking
# values of Tuple1
a, b, c = Tuple1
print(a)
print(b)
print(c)
OUTPUT
First element of
Tuple: G
Values after unpacking:
Geeks
For
Geeks
43
UPDATING TUPLES
OUTPUT
ERROR!
DELETING A TUPLE
tu = ('a', 'b',
'c') del tu[0]
print(tu)
OUTPUT
my_book=[]
ch='y'
while(ch=='y'):
2. Display Books''')
44
choice=int(input("Enter choice: "))
if(choice==1):
my_book.append(book)
elif(choice==2):
for i in my_book:
print(i)
else:
print("Invalid choice!")
print("Bye!")
OUTPUT:
2. Display Books
Enter choice: 1
components=['RADIATOR','ACCOMPRESSOR','BATTERY','ALTERNATOR','AXLE','BRA
45
components1=['CATALYTIC CONVERTER','MUFFLER','TAILPIPE']
ch='y'
while(ch=='y'):
print('''
3. Total Components
4. Components in Alphabetical
are:") print(components)
elif(choice==2):
print(components+components1)
elif(choice==3):
print("Main Components:",len(components))
print("Other Components:",len(components1))
elif(choice==4):
46
print("The components in alphabetical order
are:") components.sort()
print("Main Components:",components)
print("Sorted order")
else:
print("Invalid choice!")
print("Bye!")
OUTPUT:
3. Total Components
4. Components in Alphabetical
Sorted order
47
material=('Cement','Aggregates','Stones and Rocks','Mud and Clay',
'Concrete','Bricks','Glass','Plastic','Structural Steel',
'Electrical Items')
ch='y'
while(ch=='y'):
choice=int(input("Enter choice:
")) if(choice==1):
print(material)
elif(choice==2):
print(types)
elif(choice==3):
print(material[::-1])
elif(choice==4):
print(len(material))
elif(choice==5):
48
print(material[5])
else:
print("Invalid choice!")
print("Bye!")
OUTPUT:
1. Display Materials
5. Choose a material at
15
1. Display Materials
5. Choose a material at
Bricks
49
Do you want to continue...?
RESULT:
The tuple operations result in successful creation, modification, and retrieval of elements.
Library items include books, magazines, and journals. Car components include engine and
wheels. Laboratory materials include cement and glass. Basic operations like insertion, updating,
and deletion are achieved by converting tuples to lists and back to tuples.
50
Exp No. 6
IMPLEMENTING BASIC OPERATIONS ON SETS
a. Membership
b. Operations
c. Modifications
AIM:
To perform basic operations on sets including membership checks, set operations (union,
intersection, difference, and symmetric difference), and modifications (add, remove, update, and
clear).
ALGORITHM:
1. Define a Set ,Create a set with initial elements using curly braces {} or the set() constructor.
2. Membership Check Input the element to be checked. Use the in keyword to verify membership: If
the element exists, output True. Otherwise, output False.
51
Add an element using .add().
5. Display Results
6. End
a. Membership
1. Python IN Operator
set1 = {1, 2, 3, 4, 5}
print(6 in set1)
OUTPUT
False
2. Python NOT IN
Operator # initialized
some sequences
set1 = {1, 2, 3, 4, 5}
52
# using membership 'not in' operator
OUTPUT
True
Operations
Set Union
{1, 2, 3, 4, 5}
Set Intersection
{4, 5, 6}
3. Set Difference
53
OUTPUT
{1, 2, 3}
{1, 2, 3, 7, 8, 9}
b. Modifications
my_set = {1,
2, 3, 4} # Add
an element
my_set.add(5)
my_set.update([6, 7, 8])
# Remove an element
my_set.remove(3)
# Discard an element
54
my_set.discard(10) # No error even though 10 is not in the set
popped_element = my_set.pop()
# Clear the
set
my_set.clear()
OUTPUT
Popped element: 1
RESULT:
The program demonstrates basic set operations in Python, including membership checks,
set operations like union, intersection, difference, and symmetric difference, and modifications
using methods such as .add(), .update(), .remove(), .discard(), and .pop(). It efficiently verifies
membership, manipulates elements, and clears the set using .clear(), producing expected results
55
and showcasing the flexibility of Python sets.
56
Ex no: 7. Operations of Dictionaries
a. Python program to create a dictionary with integer keys, and print the
keys, values &
key-value pairs
c. Python program to create a dictionary with integer keys, and print the keys, values
&
key-value pairs
Aim:
Algorithm:
Step 2: Create a dictionary with integer keys and assign values to them.
Step 3: Use the .keys() method to retrieve and print all keys.
Step 4: Use the .values() method to retrieve and print all values.
Step 5: Use a loop to iterate over the dictionary and print the key-value pairs.
57
Program
print(dict_a)
for x in dict_a:
print(x)
for x in dict_a.values():
print(x)
for x, y in dict_a.items():
58
OUTPUT:
India
USA
UK
Canada
1 : India
2 : USA
3 : UK
4 : Canada
59
a. Python program to randomize (shuffle) values of dictionary
Step 4: Extract the values of the dictionary using .values() and convert them into a list.
Step 5: Use the shuffle method from the random module to randomize the list of
values.
Step 6: Reassign the shuffled values back to the original dictionary, ensuring the keys remain the
same.
Program
Initialising dictionary
Shuffling Values...
valList = list(myDict.values())
shuffle(valList)
shuffledDict = dict(mappedPairs)
60
# Printing the dictionaries...
61
print("Initial dictionary = ", end = " ")
print(myDict)
print(shuffledDict)
OUTPUT RUN 1:
RUN 2:
RUN 3:
Result:
Part (a): The program successfully creates a dictionary, prints its keys, values, and key-value
pairs.
Part (b): The program randomizes the values of a dictionary while keeping the keys intact. The
shuffled dictionary is displayed.
62
Ex no: 8. Implementing programs using Functions.
a. Factorial
c. Area of shape
a. Factoria
l Aim:
To write a python program for implementing a factorial of a given number using Recursion.
Algorithm:
Step 1: Start
Step 4: Define the base condition as the number to be lesser than or equal to 1 and return 1 if it
is.
Step 5: Otherwise call the function recursively with the number minus 1 multiplied by the
number itself.
Step 7: Stop
Program
def factorial(n):
63
if n == 0:
return 1
else:
return n * factorial(n-1)
OUTPUT
Enter a number: 5
b. largest number in
a list Aim :
Algorithm :
Step 1 : Start
Step 4 : Read each number in your python program using a for loop.
Step 6 : Define a custom function, which is an accepted number list and used to
64
Step 7 : Call this custom function and store the function result.
Step 9 : Stop
Program
def find_largest(numbers):
return max(numbers)
OUTPUT
Area of shape
Aim :
Algorithm :
Step 1 : Start.
Circle
import math
def area_circle(radius):
{area_circle(radius)}") OUTPUT
Rectangle
def area_rectangle(length, width):
OUTPUT
Triangle
def area_triangle(base, height):
OUTPUT
Result:
The functions implemented for each program performed their tasks accurately. The results were
validated by testing multiple inputs, and the outputs were as expected. Thus the program was
implemented and executed successfully.
67
Ex no: 9. Implementing programs using Strings
a. Reverse
b. Palindrome
c. Character count
d. Replacing characters
Aim:
Reverse a string.
68
Program
def reverse_string(s):
return s[::-1]
# Example usage
input_string = "hello"
OUTPUT
a. Palindrome
Program
def is_palindrome(s):
69
return s == s[::-1]
# Example usage
input_string = "madam"
if is_palindrome(input_string):
print(f"'{input_string}' is a palindrome.")
else:
OUTPUT
'madam' is a palindrome.
b. Character count
Step 2: Take a string input and a character to search for from the user.
Program
def character_count(s):
count = {}
for char in s:
70
if char in count:
count[char] +=
else:
count[char] = 1
return count
# Example usage
input_string = "hello"
OUTPUT
c. Replacing characters
Step 3: Take the character to replace and the new character as inputs.
program.
71
Program
# Example usage
OUTPUT
Result
The programs for string manipulation successfully reversed strings, identified palindromes,
counted specific character occurrences, and replaced characters. Each function provided accurate
and validated results. Examples include reversing "hello" to "olleh", identifying "madam" as a
palindrome, counting 2 occurrences of in "programming", and replacing with in "apple".
'g' 'p' 'b'
72
Ex no: 10. Implementing programs using written modules and Python Standard
Libraries (pandas, numpy, matplotlib, scipy)
numpy AIM:
To write a python program to plot a simple python graph for a straight line.
ALGORITHM:
6. Stop
PROGRAM:
import numpy as np
plt x = np.arange(1,11)
y=2*x+7
plt.title("Matplotlib demo")
pandas AIM:
ALGORITHM:
6. Stop
PROGRAM:
import numpy as np
import pandas as pd
74
mydictionary =
{'names': ['Somu',
'Kiku', 'Amol',
'Lini'], 'physics':
df_marks = pd.DataFrame(mydictionary)
print(df_marks)
75
10(c) Using Scipy - Univariate
Interpolation AIM:
ALGORITHM:
1. Start
5. Stop
PROGRAM:
x = np.arange(5, 20)
y = np.exp(x/3.0)
f = interpolate.interp1d(x, y)
x1 = np.arange(6, 12)
plt.show(
76
Result:
Implementing programs using written modules and Python libraries like Pandas, NumPy,
Matplotlib, and SciPy involves combining modular programming with powerful data
manipulation, numerical computation, and visualization tools were implemented in python.
77
E.NO:11 implementing real-time/technical applications using file handling.
To write a program to copy the content of one file into another file
Algorithm:
Step 1: Start
Step 4: Read each line from the input file and write it into the output file.
Step 5: Stop.
Program:
sourcefile = input()
targetfile = input()
texts = fileHandle.readlines()
fileHandle.close()
78
for s in texts:
fileHandle.write(s)
fileHandle.close()
Output:
Algorithm:
Step 1: Start
Step 2: Open file “book.txt” in read mode and store contents of file in file object say
fin Step 3: Read each line from the file using read() function
Step 4: Split the line to form a list of words using split() function and store it in variable
Step 5: Intitially Set the value of count_words variable to zero in which we will store
Step 6: Use for loop to read list of word stored in variable say
l. Step 7: Find the length of words in the list and print it.
79
Step 8: Close the file using close()
Program:
fin = open("book.txt","r")
str = fin.read()
l = str.split()
count_words = 0
for i in l:
count_words = count_words + 1
print(count_words)
fin.close()
Output:
25
80
C. Python Program to find longest Word in Text File
Aim:
Algorithm:
Step 1: Start
Step 2: Open text file say ‘name.txt’ in read mode using open function
Step 4: Read the whole content of text file using read function and store it in another
Step 5: Use split function on str object and store words in variable say ‘words’
Step 8: Use if loop within for loop to check the maximum length of word
Program:
fin = open("name.txt","r")
str = fin.read()
words = str.split()
81
max_len = len(max(words, key=len))
if len(word)==max_len:
longest_word =word
print(longest_word)
Output:
Encyclopedia
Result:
Thus the program for real-time/technical applications using File handling was
82
Ex No: 12 Implementing real-time / technical applications using Exception handling
AIM:
Handling.
ALGORITHM:
PROGRAM:
try:
q=n/(d-c)
print("Quotient:",q)
except ZeroDivisionError:
print("Division by Zero!")
83
OUTPUT:
Enter the value of n:
c: 5 Division by Zero!
84
12 a) VOTER’S AGE VALIDITY
ALGORITHM:
STEP2: In the if block, check if the age is greater than 18, then print “Eligible to vote”.
STEP4: If the age entered is a non-number, then the exception block is executed.
PROGRAM:
def main():
try:
if age>18:
print("Eligible to vote")
else:
except:
number") main()
OUTPUT 1:
Eligible to vote
OUTPUT 2:
85
Enter your age 14
ALGORITHM:
STEP4: If the age entered is a non-number, then the exception block is executed.
PROGRAM:
def input_number(min,max):
try:
while True:
n=int(n)
if(min<=n<=max):
print(n)
break
else:
except:
number") input_number(1,100)
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
RESULT:
Thus the program for real-time / technical applications using Exception handling was
87
Ex no :13. Python programs using Time and Calendar related functions
The aim of this program is to demonstrate the use of time and calendar modules in Python for
performing tasks related to date and time. Specifically, the program will:
1. Print the current time in a readable format using the time module.
2. Display the calendar of a specified month and year using the calendar
module.
Algorithm:
today = date.today()
88
print("Today's date:", today)
89
Output:
today = date.today()
# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
# mm/dd/y
d3 =
today.strftime("%m/%d/%y")
year d4 = today.strftime("%b-%d-
90
Output:
d1 = 27/12/2022
d2 = December 27,
2022 d3 = 12/27/22
d4 = Dec-27-2022
import calendar
yy = 2014 #
year
mm = 11 # month
# mm = int(input("Enter month:
print(calendar.month(yy, mm))
91
November 2014
Mo Tu We Th Fr Sa Su
12
34 5 67 89
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Result: