Experiment 1
Aim
You are developing a program to manage a simple library system. The system
allows the user to:
• Search for a book by title (sequential algorithm)
• Check if a user is eligible for membership based on age (selective algorithm - if
age >= 18, eligible; else, not eligible)
• Keep track of borrowed books with a maximum limit of 5 books (iterative
algorithm to ensure no more than 5 books are borrowed).
Task:
• Write the algorithms for each functionality.
• Represent the algorithms in a flowchart.
• Implement the algorithms in Python and test them using sample inputs.
Algorithms
(a) Sequential Algorithm – Search for a Book
Algorithm:
1. Start
2. Input the list of available books
3. Input the title of the book to search
4. For each book in the list:
o If the book matches the search title → Display “Book Found” and
stop
5. If no match is found → Display “Book Not Found”
6. End
(b) Selective Algorithm – Check Membership Eligibility
Algorithm:
1. Start
2. Input the user’s age
3. If age ≥ 18 → Display “Eligible for Membership”
4. Else → Display “Not Eligible for Membership”
5. End
(c) Iterative Algorithm – Borrow Books (Max 5)
Algorithm:
1. Start
2. Set borrowed_books = 0
3. While borrowed_books < 5 do:
o Ask user: “Do you want to borrow a book? (yes/no)”
o If “yes” → Increase borrowed_books by 1
o If “no” → Break loop
4. If borrowed_books == 5 → Display “Borrowing limit reached”
5. Display total number of books borrowed
6. End
Flowcharts
(a) Book Search
⭘Start
⬒ Enter Book List, Title
▭ For each book in list
◇Title matches?
/ \
Yes No
| |
⬒ "Book Found" Continue loop
⭘End
(b) Membership Eligibility
⭘Start
⬒ Input Age
◇Age ≥ 18 ?
/ \
Yes No
| |
⬒ "Eligible" ⬒ "Not Eligible"
⭘End
(c)Borrow Books
⭘Start
↓
▭ borrowed_books = 0
↓
◇borrowed_books < 5 ?
/ \
Yes No
| |
⬒ Ask: Borrow book?
↓
◇Choice = yes ?
/ \
Yes No
| |
▭ borrowed_books = borrowed_books + 1 → End Loop
↓
Back to borrowed_books < 5 ?
Program
# (a) Sequential Algorithm - Search for a Book
def search_book(book_list, title):
for book in book_list:
if book.lower() == title.lower():
return "Book Found"
return "Book Not Found"
# (b) Selective Algorithm - Membership Eligibility
def check_membership(age):
if age >= 18:
return "Eligible for Membership"
else:
return "Not Eligible for Membership"
# (c) Iterative Algorithm - Borrow Books
def borrow_books():
borrowed_books = 0
while borrowed_books < 5:
choice = input("Do you want to borrow a book? (yes/no):
").lower()
if choice == "yes":
borrowed_books += 1
print(f"Book borrowed successfully! Total =
{borrowed_books}")
else:
break
if borrowed_books == 5:
print("Borrowing limit reached!")
print(f"Total books borrowed: {borrowed_books}")
# ----------- Testing the Functions -----------
# Test (a) Search Book
books = ["Python Programming", "Data Structures", "Algorithms", "AI
Basics"]
print(search_book(books, "Algorithms")) # Expected: Book Found
print(search_book(books, "Java")) # Expected: Book Not Found
# Test (b) Membership Eligibility
print(check_membership(20)) # Expected: Eligible for Membership
print(check_membership(15)) # Expected: Not Eligible for
Membership
# Test (c) Borrow Books (interactive)
# Uncomment below to test interactively
# borrow_books()
Experiment -2
Aim
A delivery company needs to find the shortest route to deliver packages across
three cities (A, B, and C). The distance between the cities is known:
• A to B = 50 km
• A to C = 70 km
• B to C = 30 km
Task:
Use means-end analysis to determine the best delivery route that minimizes
travel distance.
Steps:
• Break the problem down into subproblems.
• Write a step-by-step algorithm showing how means-end analysis is used to find
the shortest path.
• Create a flowchart representing the algorithm and implement it using Python or
pseudocode.
1)Break the problem into subproblems (Means–End Analysis)
State representation: current city, set of unvisited cities; known pairwise
distances.
Goal state: all cities visited (A, B, C).
Difference measure: number of unvisited cities (and pick the least-cost step
that reduces it).
Operators: move from current city to any unvisited city.
Strategy (MEA): repeatedly choose the move that most reduces the
difference with the smallest cost (nearest unvisited city).
Assumption: start at A and visiting all once is enough (no return to A).
2) Step-by-step algorithm (MEA)
1. Set current = A, unvisited = {B, C}, path = [A], total =
0.
2. While unvisited is not empty:
a. For each city u in unvisited, look up distance(current, u).
b. Choose next_city with the minimum distance (operator that best
reduces the difference).
c. Append next_city to path; add that distance to total.
d. Set current = next_city and remove it from unvisited.
3. Output path and total.
3) Flowchart (ASCII)
+-----------------------+
| Start |
+-----------+-----------+
|
v
+-----------------------+
| current := A |
| unvisited := {B, C} |
| path := [A]; total=0 |
+-----------+-----------+
|
v
+------+------+
| unvisited ? |----No----->+--------------+
| empty | | Output |
+------+------+\ | path,total |
| \ Yes +------+-------+
| | End |
v +--------------+
+---------------------------+
| For u in unvisited: |
| compute d(current, u) |
+-------------+-------------+
|
v
+---------------------------+
| next := argmin d |
| total += d(current, next) |
| path.append(next) |
| current := next |
| unvisited.remove(next) |
+-------------+-------------+
|
v
(loop)
4) Python implementation (MEA: nearest unvisited next step)
# Distances (undirected)
dist = {
('A', 'B'): 50, ('B', 'A'): 50,
('A', 'C'): 70, ('C', 'A'): 70,
('B', 'C'): 30, ('C', 'B'): 30
}
def d(x, y):
return dist[(x, y)]
def mea_shortest_route(start='A'):
unvisited = {'A', 'B', 'C'} - {start}
current = start
path = [current]
total = 0
while unvisited:
# Choose the nearest unvisited city (operator
that best reduces the difference)
next_city = min(unvisited, key=lambda u:
d(current, u))
total += d(current, next_city)
path.append(next_city)
unvisited.remove(next_city)
current = next_city
return path, total
# Run MEA from A
route, distance_km = mea_shortest_route('A')
print("Best route (MEA):", " → ".join(route))
print("Total distance:", distance_km, "km")
output
Best route (MEA): A → B → C
Total distance: 80 km
Experiment – 3
Aim
Write a Python program that takes the age of a user as input and determines the
life stage they are in based on the following conditions:
• 0–12 years: "Child"
• 13–19 years: "Teenager"
• 20–35 years: "Young Adult"
• 36–60 years: "Adult"
Above 60 years: "Senior"
Algorithm
1. Start
2. Input the user’s age.
3. If 0 <= age <= 12 → Life stage = "Child".
4. Else if 13 <= age <= 19 → Life stage = "Teenager".
5. Else if 20 <= age <= 35 → Life stage = "Young Adult".
6. Else if 36 <= age <= 60 → Life stage = "Adult".
7. Else if age > 60 → Life stage = "Senior".
8. Display the life stage.
9. End.
# Program to determine life stage based on age
# Step 1: Input
age = int(input("Enter your age: "))
# Step 2: Determine life stage using conditions
if 0 <= age <= 12:
stage = "Child"
elif 13 <= age <= 19:
stage = "Teenager"
elif 20 <= age <= 35:
stage = "Young Adult"
elif 36 <= age <= 60:
stage = "Adult"
elif age > 60:
stage = "Senior"
else:
stage = "Invalid age entered"
# Step 3: Display result
print("Life Stage:", stage)
Output
Input:
Enter your age: 25
Output:
Life Stage: Young Adult
Experiment – 4
Aim
Write a Python program that takes a string input from the user and counts the
number of vowels and consonants in the string.
• Use variables and appropriate data types to store and manipulate the input.
• Display the results, showing the counts of vowels and consonants separately.
Algorithm
1. Start
2. Take a string input from the user.
3. Initialize two counters: vowel_count = 0, consonant_count = 0.
4. Define vowels: a, e, i, o, u (both uppercase & lowercase).
5. For each character in the string:
o If the character is a letter:
If it’s in vowels → increment vowel_count.
Else → increment consonant_count.
6. Print vowel_count and consonant_count.
7. End.
Program
# Program to count vowels and consonants in a string
# Step 1: Input from user
text = input("Enter a string: ")
# Step 2: Initialize counters
vowel_count = 0
consonant_count = 0
# Step 3: Define vowels
vowels = "aeiouAEIOU"
# Step 4: Loop through each character
for char in text:
if char.isalpha(): # check if it's a letter
if char in vowels:
vowel_count += 1
else:
consonant_count += 1
# Step 5: Display results
print("Number of vowels:", vowel_count)
print("Number of consonants:", consonant_count)
Output
Input:
Enter a string: Hello World
Output:
Number of vowels: 3
Number of consonants: 7
Experiment -5
Aim
Write a Python program that accepts a number from the user and checks if it is
even or odd.
• If the number is even, display "Even Number,"otherwise display "Odd Number.
Use decision-making statements (if-else) to determine the output.
Algorithm
1. Start
2. Input a number from the user.
3. Check remainder when the number is divided by 2 (num % 2).
o If remainder = 0 → print "Even Number".
o Else → print "Odd Number".
4. End.
Program
# Program to check if a number is even or odd
# Step 1: Input from user
num = int(input("Enter a number: "))
# Step 2: Decision-making using if-else
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Output
Input:
Enter a number: 10
Output:
Even Number
Input:
Enter a number: 7
Output:
Odd Number
Experiment -6
Aim
Write a simple Python program to take two numbers as input from the user and
perform basic arithmetic operations (addition, subtraction, multiplication,
division, modulus, floor division, exponentiation).
• Display the results for each operation.
Algorithm
1. Start
2. Accept two numbers as input from the user.
3. Perform operations:
o Addition (+)
o Subtraction (-)
o Multiplication (*)
o Division (/)
o Modulus (%)
o Floor Division (//)
o Exponentiation (**)
4. Display the results.
5. End
Program
# Program to perform basic arithmetic operations
# Step 1: Take input from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Step 2: Perform operations
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2 if num2 != 0 else "Undefined
(division by zero)"
modulus = num1 % num2 if num2 != 0 else "Undefined
(modulus by zero)"
floor_division = num1 // num2 if num2 != 0 else
"Undefined (floor division by zero)"
exponentiation = num1 ** num2
# Step 3: Display results
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Modulus:", modulus)
print("Floor Division:", floor_division)
print("Exponentiation:", exponentiation)
Output
Input:
Enter first number: 10
Enter second number: 3
Output:
Addition: 13.0
Subtraction: 7.0
Multiplication: 30.0
Division: 3.3333333333333335
Modulus: 1.0
Floor Division: 3.0
Exponentiation: 1000.0
Experiment -7
Aim
Write a Python program to define a function that calculates the factorial of a
number provided by the user.
• Use a for loop to calculate the factorial.
• Demonstrate how to call the function in the main program and display the
result.
Algorithm
Start
Define a function factorial(n)
o Initialize fact = 1
o Repeat for i from 1 to n (inclusive):
Multiply fact = fact * i
o Return fact
In the main program:
o Read a number num from the user
o Call the function: result = factorial(num)
o Display the result
End
Program
# Function to calculate factorial
def factorial(n):
fact = 1
for i in range(1, n + 1): # Loop from 1 to n
fact *= i
return fact
# Main program
num = int(input("Enter a number: "))
# Call the function and display result
result = factorial(num)
print(f"The factorial of {num} is {result}")
Output
Enter a number: 6
The factorial of 6 is 720
Experiment -8
Aim
Write a Python program that defines a recursive function to calculate the sum of
all integers from 1 to a given number n.
Algorithm:
Start
Define a recursive function recursive_sum(n)
o If n == 1 → return 1 (base case)
o Otherwise → return n + recursive_sum(n - 1)
In the main program:
o Read a number num from the user
o If num > 0 → call the function recursive_sum(num)
o Store the result in a variable result
o Display the result
o Else → display "Enter a positive integer"
End
Program
# Recursive function to calculate sum from 1 to n
def recursive_sum(n):
if n == 1: # Base case
return 1
else:
return n + recursive_sum(n - 1) # Recursive
call
# Main program
num = int(input("Enter a positive integer: "))
if num > 0:
result = recursive_sum(num)
print(f"The sum of integers from 1 to {num} is
{result}")
else:
print("Please enter a positive integer.")
Output
Enter a positive integer: 6
The sum of integers from 1 to 6 is 21
Experiment -9
Aim
Write a Python program that takes a list of numbers and performs the following
operations using inbuilt functions:
• Find the maximum and minimum numbers in the list.
• Sort the list in ascending and descending order.
• Find the sum and average of the numbers in the list.
Algorithm
1. Start
2. Read a list of numbers from the user.
3. Use the max() function to find the maximum number in the list.
4. Use the min() function to find the minimum number in the list.
5. Use the sorted() function to sort the list in ascending order.
6. Use sorted(list, reverse=True) to sort the list in descending
order.
7. Use the sum() function to find the sum of the numbers.
8. Calculate the average as sum / length of list.
9. Display all results (maximum, minimum, sorted lists, sum, average).
10.End
Program
# Main program
# Step 1: Take input list of numbers from user
numbers = list(map(int, input("Enter numbers separated
by space: ").split()))
# Step 2: Perform operations using inbuilt functions
maximum = max(numbers)
minimum = min(numbers)
ascending = sorted(numbers)
descending = sorted(numbers, reverse=True)
total_sum = sum(numbers)
average = total_sum / len(numbers)
# Step 3: Display results
print("Maximum number:", maximum)
print("Minimum number:", minimum)
print("Sorted in ascending order:", ascending)
print("Sorted in descending order:", descending)
print("Sum of numbers:", total_sum)
print("Average of numbers:", average)
Output
Enter numbers separated by space: 10 5 8 20 15
Maximum number: 20
Minimum number: 5
Sorted in ascending order: [5, 8, 10, 15, 20]
Sorted in descending order: [20, 15, 10, 8, 5]
Sum of numbers: 58
Experiment -10
Aim
Write a Python program to create two NumPy arrays of the same shape.
• Perform element-wise addition, subtraction, multiplication, and division on the
arrays.
• Display the results of each operation.
Algorithm
1. Start
2. Import the numpy library.
3. Create two NumPy arrays of the same shape.
4. Perform the following element-wise operations:
o Addition: array1 + array2
o Subtraction: array1 - array2
o Multiplication: array1 * array2
o Division: array1 / array2
5. Display the results of all operations.
6. End
Program
import numpy as np
# Step 1: Create two arrays of same shape
array1 = np.array([10, 20, 30, 40, 50])
array2 = np.array([2, 4, 6, 8, 10])
# Step 2: Perform element-wise operations
addition = array1 + array2
subtraction = array1 - array2
multiplication = array1 * array2
division = array1 / array2 # element-wise division
# Step 3: Display results
print("Array 1:", array1)
print("Array 2:", array2)
print("Element-wise Addition:", addition)
print("Element-wise Subtraction:", subtraction)
print("Element-wise Multiplication:", multiplication)
print("Element-wise Division:", division)
Output
Array 1: [10 20 30 40 50]
Array 2: [ 2 4 6 8 10]
Element-wise Addition: [12 24 36 48 60]
Element-wise Subtraction: [ 8 16 24 32 40]
Element-wise Multiplication: [ 20 80 180 320 500]
Element-wise Division: [5. 5. 5. 5. 5.]
Experiment -11
Aim
Write a Python program to create a 2D NumPy array and perform the following
operations:
• Calculate the mean, median, and standard deviation of the array.
• Use NumPy functions for these calculations and display the results.
Algorithm
1. Start
2. Import the numpy library.
3. Create a 2D NumPy array with some values.
4. Use NumPy functions to perform operations:
o Mean → np.mean(array)
o Median → np.median(array)
o Standard Deviation → np.std(array)
5. Display the results.
6. End
Program
import numpy as np
# Step 1: Create a 2D NumPy array
array = np.array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
# Step 2: Perform statistical operations
mean_value = np.mean(array)
median_value = np.median(array)
std_deviation = np.std(array)
# Step 3: Display results
print("2D Array:\n", array)
print("Mean of array:", mean_value)
print("Median of array:", median_value)
print("Standard Deviation of array:", std_deviation)
Output
2D Array:
[[10 20 30]
[40 50 60]
[70 80 90]]
Mean of array: 50.0
Median of array: 50.0
Standard Deviation of array: 25.81988897471611
Experiment -12
Aim
Write a Python program to read a text file containing a list of names (one name
per line) and display the names on the console.
• Handle exceptions for file not found.
Algorithm
1. Start
2. Use a try-except block to handle file operations.
3. Open the text file in read mode.
4. Read all lines from the file.
5. For each line, strip extra spaces/newlines and display the name.
6. If the file is not found, display an error message.
7. End
Program
# Program to read names from a text file and display
them
try:
# Open the file in read mode
with open("names.txt", "r") as file:
print("List of Names:")
for line in file:
name = line.strip() # Remove extra
spaces/newlines
if name: # Avoid empty lines
print(name)
except FileNotFoundError:
print("Error: The file 'names.txt' was not found.")
names.txt File
Alice
Bob
Charlie
David
Eva
Output
List of Names:
Alice
Bob
Charlie
David
Eva
Experiment -13
Aim
Write a Python program to create a CSV file containing student names and their
grades.
• Then, read the CSV file and display its contents.
Algorithm
1. Start
2. Import the csv module.
3. Create a list containing student names and their grades (include a header
row).
4. Open a CSV file in write mode.
5. Write the data into the CSV file using csv.writer().
6. Close the file.
7. Open the same CSV file in read mode.
8. Read its contents using csv.reader() and display them row by row.
9. Handle any file-related errors if necessary.
10.End
Program
import csv
# Step 1: Data for students
students = [
["Name", "Grade"], # Header row
["Alice", "A"],
["Bob", "B+"],
["Charlie", "A-"],
["David", "B"],
["Eva", "A+"]
]
# Step 2: Write data to CSV file
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(students)
print("CSV file 'students.csv' created
successfully.\n")
# Step 3: Read data from CSV file
print("Contents of the CSV file:")
with open("students.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
Output
CSV file 'students.csv' created successfully.
Contents of the CSV file:
['Name', 'Grade']
['Alice', 'A']
['Bob', 'B+']
['Charlie', 'A-']
['David', 'B']
['Eva', 'A+']