244MCC112L-MCA Python Lab Manual (1)
244MCC112L-MCA Python Lab Manual (1)
244MCC112L-MCA Python Lab Manual (1)
Aim:
To understand and implement a basic concept of swapping two values without using a temporary
variable, and to demonstrate simple variable manipulation techniques in Python.
Algorithm:
Program:
# Example
a=5
b = 10
print(f"Before swap: a = {a}, b = {b}")
a, b = swap_values(a, b)
print(f"After swap: a = {a}, b = {b}")
Output:
Before swap: a = 5, b = 10
After swap: a = 10, b = 5
Result:
Aim:
To practice manipulating collections of variables (lists) by shifting or rotating elements, which helps
in understanding indexing and list operations in Python.
Algorithm:
Program:
def circulate_values(arr):
# Rotate left by 1
return arr[1:] + [arr[0]]
# Example
arr = [1, 2, 3, 4, 5]
print(f"Before circulation: {arr}")
arr = circulate_values(arr)
print(f"After circulation: {arr}")
Output:
Result:
Aim:
To apply basic geometry using the distance formula and demonstrate how to use mathematical
functions in Python, such as square root and exponentiation.
Algorithm:
Program:
import math
# Example
x1, y1 = 1, 2
x2, y2 = 4, 6
print(f"Distance: {distance_between_points(x1, y1, x2, y2)}")
Output:
Distance: 5.0
Result:
Aim:
To do a Python program for implementing scientific problems using Conditionals and Iterative loops.
Algorithm:
• Define the conditions or parameters (e.g., checking for prime numbers or calculating
factorial).
• Set up the loop structure (for/while loop) for iteration.
• Within the loop, use conditionals (if/else) to check and handle specific conditions.
• For example, if checking for a prime, check if the number has any divisors other than 1 and
itself.
• Perform required operations (e.g., add to a sum or accumulate results) within the loop.
• Exit the loop and display results after completion.
Program:
# Input numbers
num = int(input("Enter a number to check if it is prime: "))
fact_num = int(input("Enter a number to calculate its factorial: "))
Result:
Linear Search
Aim:
To understand the concept of sequential searching and how to efficiently find an element in an
unsorted list by checking each item one by one.
Algorithm:
Program:
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
# Example
arr = [1, 4, 6, 7, 8]
target = 6
print(f"Index of {target}: {linear_search(arr, target)}")
Output:
Index of 6: 2
Result:
Binary Search
Aim:
To implement a more efficient search method for sorted lists, using divide-and-conquer techniques
to quickly locate an item by repeatedly dividing the search space in half.
Algorithm:
Program:
# Example
arr = [10, 4, 7, 1, 3]
target = 7
print(f"Index of {target}: {binary_search(arr, target)}")
Output:
Index of 7: 2
Result:
Selection Sort
Aim:
To understand the sorting process by selecting the smallest element in each pass and swapping it
into its correct position, and to practice working with loops and conditional statements.
Algorithm:
Program:
def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
# Example
arr = [64, 34, 25, 12, 22, 11, 90]
print(f"Sorted array: {selection_sort(arr)}")
Output:
Result:
Insertion Sort
Aim:
To practice sorting by gradually building a sorted portion of the list and inserting elements in the
correct position, thereby demonstrating the concept of "insertion" sorting.
Algorithm:
Program:
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
# Example
arr = [64, 34, 25, 12, 22, 11, 90]
print(f"Sorted array: {insertion_sort(arr)}")
Output:
Result:
Merge Sort
Aim:
Algorithm:
• If the list has more than one element, divide the list into two halves.
• Recursively apply merge sort to each half.
• Merge the two sorted halves into a single sorted list.
• Return the merged list.
• Repeat until all lists are of length 1.
• Combine the sorted lists back into one sorted list.
Program:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
merge_sort(left)
merge_sort(right)
i=j=k=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
Output:
Result:
Quick Sort
Aim:
To implement a recursive sorting algorithm that selects a pivot element and partitions the list into
smaller sublists, using the concept of recursion and partitioning.
Algorithm:
• Choose a pivot element from the list (typically the last element).
• Partition the list into two sublists: elements smaller than the pivot and elements greater than
the pivot.
• Recursively apply quick sort to each sublist.
• Merge the sublists and pivot back into a sorted list.
• Repeat until all sublists are of length 1.
• Return the sorted list.
Program:
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
less_than_pivot = [x for x in arr[1:] if x <= pivot]
greater_than_pivot = [x for x in arr[1:] if x > pivot]
return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot)
# Example
arr = [38, 27, 43, 3, 9, 82, 10]
print(f"Sorted array: {quick_sort(arr)}")
Output:
Result:
Aim:
To understand and apply basic data structures like lists and tuples, and practice common operations
like adding, removing, and accessing elements in these structures.
Algorithm:
Program:
def list_and_tuple_example():
# List
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
# Tuple
my_tuple = (1, 2, 3, 4, 5)
print(f"List: {my_list}")
print(f"Tuple: {my_tuple}")
list_and_tuple_example()
Output:
List: [1, 2, 3, 4, 5, 6]
Tuple: (1, 2, 3, 4, 5)
Result:
Aim:
To work with unordered collections of unique elements, applying operations like adding, removing,
and checking membership in a set and dictionary.
Algorithm:
Program:
# Creating a dictionary
student_grades = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}
Output:
Alice's grade: 85
Bob's grade: 92
Updated student grades: {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 88}
Updated Alice's grade: 90
Student grades after deleting Charlie: {'Alice': 90, 'Bob': 92, 'David': 88}
Is Bob in the dictionary? True
Result:
Aim:
To understand the concept of functions in Python by defining reusable code blocks that take
parameters and return values, enhancing code modularity and clarity.
Algorithm:
Program:
if __name__ == "__main__":
main()
Output:
Addition: 8
Prime check: True
Factorial: 120
Reversed string: olleh
Max in list: 5
Average of list: 3.0
List without duplicates: [1, 2, 3, 4]
Result:
Aim:
To manipulate and work with string data types in Python, using various string methods and
operations to perform transformations and analysis on text data.
Algorithm:
Program:
Initialize strings
str1, str2 = "Hello", "World"
# Concatenate strings
print("Concatenated:", str1 + " " + str2)
# Repeat string
print("Repeated:", str1 * 3)
# String length
print("Length:", len(str1 + str2))
# Slicing
print("Sliced:", (str1 + str2)[0:5])
# Replace a substring
print("Replaced:", (str1 + str2).replace("World", "Universe"))
# Split string
print("Split:", (str1 + " " + str2).split())
# String formatting
name, age = "Alice", 25
print(f"Formatted: Hello {name}, you are {age} years old.")
# Strip spaces
print("Stripped:", " Hello World! ".strip())
Output:
Result:
10. Implementing programs using written modules and Python Standard Libraries
Aim:
To write a python program for Implementing programs using written modules and Python Standard
Libraries (pandas, numpy, Matplotlib, scipy)
Algorithm:
• Import necessary libraries (e.g., import pandas as pd, import numpy as np).
• Create data structures (e.g., DataFrame, numpy arrays).
• Perform the required computations or analysis (e.g., apply functions, perform matrix
operations).
• Use libraries to visualize data (e.g., matplotlib.pyplot to plot graphs).
• Perform any necessary statistical analysis using scipy.
• Return or display results based on the library functions used.
Program:
# Creating a DataFrame
df = pd.DataFrame(data)
Output:
Result:
Aim:
To introduce file input/output operations in Python, enabling reading from and writing to files, which
is fundamental for handling external data in real-world applications.
Algorithm:
Program:
# 1. Writing to a File
with open("example.txt", "w") as file:
file.write("Hello, this is a sample text!\n")
file.write("File handling in Python is easy.\n")
Output:
File exists.
List written to file.
File closed manually.
Result:
Aim:
To implement error handling in Python programs using try, except, and finally blocks, ensuring that
the program handles exceptions gracefully and continues execution when possible.
Algorithm:
• Begin a try block where you place the code that might raise an exception.
• Use except to catch specific exceptions (e.g., ValueError, ZeroDivisionError).
• Optionally, handle exceptions using else if no exception occurs.
• Use finally to clean up resources (e.g., closing files) regardless of whether an exception
occurred.
• Optionally, raise custom exceptions using raise.
• Display appropriate messages for each case (error or success).
Program:
# Test cases
divide_numbers(10, 2) # Correct division
print("-" * 40)
divide_numbers(10, 0) # Division by zero
print("-" * 40)
divide_numbers(10, 'a') # Invalid type for division
Output:
Result:
Aim:
To learn object-oriented programming (OOP) concepts by creating classes and instances (objects),
and to demonstrate how to define properties and behaviors (methods) for objects in Python.
Algorithm:
Program:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"Car Info: {self.year} {self.make} {self.model}")
# Create an instance
car1 = Car("Toyota", "Corolla", 2020)
car1.display_info()
Output:
Result: