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

Python Lab Record(Week-1,2,3,5,6,7)

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

Python Lab Record(Week-1,2,3,5,6,7)

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 111

WEEK-1 Python Programs on Lists & Dictionaries

PROGRAM-1
AIM: Write a python script to Use a for loop to print a triangle like the one below. Allow the user to
specify how high the triangle should be.
*
**
***
****
DESCRIPTION:
This program prints a right-angled triangle star (*) pattern using nested loops. The user enters a
number (num) to determine the number of rows. The outer loop controls the rows, while the inner
loop prints stars (*) in each row. print('*', end=' ') ensures stars are printed in the same line, and
print() moves to the next line.
Key Concepts Used:
1. Loops (for loop) – Outer loop controls rows, inner loop prints stars.
2. range() – Generates a sequence for loop iteration.
3. Nested Loops – Inner loop runs based on the outer loop's value.
4. Printing (print()) – end=' ' prevents new lines, while print() moves to the next row.
5. User Input (input()) – Takes input and converts it to an integer.
This results in a star pattern where each row has stars equal to the row number.
SOURCE CODE:
num=int(input("Enter the number of rows"))
for i in range(1,num+1,1):
for j in range(1,i+1,1):
print('*',end=' ')
print()
OUTPUT:
Enter the number of rows 5
*
**
***
****
*****
PROGRAM-2
AIM: Write a python script to Generate a random number between 1 and 10. Ask the user to guess
the number and print a message based on whether they get it right or not guess the random number
DESCRIPTION:
This program generates a random number between 1 and 10 and asks the user to guess it. It then
compares the user’s input with the randomly generated number and displays whether the guess is
correct or not.
Key Concepts Used:
1. Random Number Generation (random.randint(a, b)) – Generates a random integer
between 1 and 10.
2. User Input (input()) – Takes a number from the user and converts it to an integer.
3. Conditional Statements (if-else) – Compares the user’s guess with the random number and
prints the result accordingly.
4. Printing (print()) – Displays the result and the generated random number.
This program allows users to test their luck by guessing a randomly generated number.
SOURCE CODE:
import random
randnum=random.randint(1,10)
num=int(input("Enter a number"))
if randnum==num:
print("Your guess is correct")
print("Random number is ",randnum)
else:
print("Try again")
print("Random number is ",randnum)
OUTPUT:
Enter a number 5
Try again
Random number is 6
PROGRAM-3
AIM: Write a python script to write a program that asks the user to enter a word and prints out
whether that word contains any vowels. Prints vowels.
DESCRIPTION:
This program checks whether a given word contains at least one vowel. It iterates through each
character of the word and stops as soon as it finds a vowel. If a vowel is found, it prints that the
word.
Key Concepts Used:
1. User Input (input()) – The program takes a word as input from the user.
2. List (vowelslist) – A predefined list stores both uppercase and lowercase vowels for easy
checking.
3. Loop (for loop) – Iterates through each character in the input word.
4. Conditional Statement (if) – Checks if the current character is a vowel.
5. Counter Variable (c) – Used to keep track of whether a vowel is found.
6. Break Statement (break) – Immediately stops checking further once a vowel is found,
optimizing performance.
7. Final Check (if-else) – Based on the counter’s value, it prints whether vowels are present or
not.
This program efficiently determines if a word contains vowels by stopping early upon finding the
first vowel, making it more optimized than checking the entire word.
SOURCE CODE:
word=input("Enter a word:")
vowelslist=['a','e','i','o','u','A','E','I','O','U']
c=0
for i in word:
if i in vowelslist:
c=c+1
break
if(c!=0):
print("The word contains vowels")
else:
print("The word does not contain vowels")
OUTPUT:
Enter a word: python
The word contains vowels
PROGRAM-4
AIM: Write a python script to write a function called first_diff that is given two strings and returns
the first location in which the strings differ. If the strings are identical, it should return -1
DESCRIPTION:
This program finds the first position where two input strings differ. It compares characters at
corresponding positions and returns the index of the first mismatch. If the strings are identical, it
returns -1.
Key Concepts Used:
1. User Input (input()) – Takes two strings from the user.
2. Function Definition (def first_diff(s1, s2)) – Defines a function to compare two strings.
3. Loop with zip() – Iterates through both strings simultaneously, comparing characters.
4. Conditional Statement (if-else) – Checks if the strings are different or identical.
5. Index Tracking (loc) – Keeps count of matching characters before the first difference.
6. Return Statement (return) – Returns the position of the first mismatch or -1 if both strings
are the same.
7. Printing (print()) – Displays the location where the strings differ.
SOURCE CODE:
def first_diff(s1,s2):
loc=0
if s1!=s2:
for i,j in zip(s1,s2):
if i==j:
loc+=1
return loc
else:
return -1
string1=input("Enter string1:")
string2=input("Enter string2:")
print("First location in which the strings differ:",first_diff(string1,string2))
OUTPUT:
Enter string1: GVPW
Enter string2: GVPCEW
First location in which the strings differ: 3
PROGRAM-5
AIM: Write a program that asks the user for an integer and creates a list that consists of the factors
of that integer
DESCRIPTION:
This program finds and displays all the factors of a given number. It iterates through numbers from 1
to n and checks which numbers divide n without a remainder.
Key Concepts Used:
1. User Input (input()) – Takes an integer n from the user.
2. List (factorlist) – Stores the factors of n.
3. Loop (for loop) – Iterates from 1 to n to check for factors.
4. Conditional Statement (if) – Checks if n is divisible by i (n % i == 0).
5. List Method (append()) – Adds valid factors to the factorlist.
6. Printing (print()) – Displays the list of factors.
This program efficiently determines and prints all factors of a given number.
SOURCE CODE:
n=int(input("Enter a number"))
factorlist=[]
for i in range(1,n+1):
if(n%i==0):
factorlist.append(i)
print("Factors of",n,"are",factorlist)
OUTPUT:
Enter a number 25
Factors of 25 are [1, 5, 25]
PROGRAM-6
AIM: Write a program that generates 100 random integers that are either 0 or 1. Then find the
longest run of zeros, the largest number of zeros in a row. For instance, the longest run of zeros in
[1,0,1,1,0,0,0,0,1,0,0] is 4.
DESCRIPTION:
This program generates a random list of 0s and 1s, then finds the longest consecutive sequence of 0s
in the list.
Part 1: Generating a Random List
1. Random Number Generation (random.choices()) – Creates a list of 0s and 1s of length 100.
2. Function Definition (random_list(length=100)) – Defines a function with a default length of
100.
3. List Output (print(rl)) – Displays the generated list.
Part 2: Finding the Longest Sequence of 0s
4. Module (itertools.groupby()) – Groups consecutive identical elements.
5. List Comprehension (max(len(list(g)))) – Finds the longest sequence where k == 0.
6. Function Definition (largest_row_of_zeros(l)) – Identifies the longest stretch of consecutive
0s.
7. Function Call (largest_row_of_zeros(rl)) – Executes the function on the generated list.
SOURCE CODE:
#PART1
import random
def random_list(length=100):
return random.choices((0, 1), k=length)
rl=random_list()
print(rl)#PART2
import itertools
def largest_row_of_zeros(l):
return max(len(list(g)) for k, g in itertools.groupby(l) if k == 0)
largest_row_of_zeros(rl)
OUTPUT:
[0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0,
0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1,
0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1]
3
PROGRAM-7
AIM: Write a python script that removes any repeated items from a list so that each item appears at
most once. For instance, the list [1,1,2,3,4,3,0,0] would become [1,2,3,4,0].
DESCRIPTION:
This program generates a random list of integers and removes duplicates using two methods: set()
and membership operators.
Key Concepts Used:
1. Random Number Generation (random.randint(1,10)) – Creates a list of random integers
between 1 and 10.
2. List Comprehension – Generates a list of 50 numbers efficiently.
3. Set Data Structure (set()) – Automatically removes duplicates and converts back to a list.
4. Loop with Membership Operator (if i not in result_list) – Iterates through the list and adds
only unique elements.
5. List Concatenation (result_list+=[i]) – Dynamically appends unique elements.
This program efficiently removes duplicate values from a randomly generated list using two different
approaches, ensuring uniqueness in the output.
SOURCE CODE:
import random
def random_list(length=50):
return [random.randint( 1,10) for i in range(length)]
rl=random_list()
print(rl) #solution1-using set() removes duplicates
result=list(set(rl))
print((result)) #solution2 using membership operators
result_list=[]
for i in rl:
if i not in result_list:
result_list+=[i]
print(result_list)
OUTPUT:
[3, 10, 6, 9, 1, 2, 7, 7, 3, 7, 8, 9, 7, 2, 7, 1, 4, 1, 3, 7, 6, 4, 2, 4, 7, 7, 5, 10, 6, 5, 6, 6, 2, 5, 4, 6, 7, 6, 6,
10, 8, 5, 10, 2, 4, 4, 4, 1, 4, 4]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[3, 10, 6, 9, 1, 2, 7, 8, 4, 5]
PROGRAM-8
AIM: Write a python script to write a function called number_of_factors that takes an integer and
returns how many factors the number has solution using anonymus function lambda.
DESCRIPTION:
This program calculates the number of factors of a given number using the filter() function and a
lambda expression. It efficiently finds divisors and counts them, optimizing performance by reducing
iterations.
Key Concepts Used:
1. User Input (input()) – Takes an integer num from the user to determine its factors. The input
is converted to an integer using int() to ensure numerical operations.
2. Lambda Function (lambda i: n % i == 0) – Defines an anonymous function that checks if i
is a factor of n. It returns True if n is divisible by i without a remainder, helping filter valid
factors.
3. filter() Function – Applies the lambda function to a range of numbers and filters out only the
valid factors. This reduces the need for explicit looping and improves readability.
4. Range Optimization (range(1, int(n/2) + 1)) – Iterates only up to half of n instead of
checking all numbers up to n. Since no factor (except n itself) can be greater than n/2, this
optimization speeds up execution.
5. List Conversion (list(filter(...))) – Converts the filtered result into a list, making it easy to
display the factors. Lists allow indexed access and can be printed directly for better
visualization.
6. Length Calculation (len(factors) + 1) – Determines the number of factors by counting the
elements in the list and adding 1. The +1 accounts for n itself, which was excluded from the
filtering process.
7. Printing (print()) – Displays the list of factors and their count. It provides a clear output
showing both the individual factors and the total number of factors.
SOURCE CODE:
def number_of_factors(n):
factors = list(filter(lambda i: n%i == 0, range(1,int(n/2)+1)))
print(factors)
return len(factors) + 1
num=int(input("Enter number:"))
print("The number of factors are",number_of_factors(num))
OUTPUT:
Enter number: 36
[1, 2, 3, 4, 6, 9, 12, 18]
The number of factors are 9
PROGRAM-9
AIM: Write a python script to sort a list alphabetically in a dictionary.
DESCRIPTION:
This program defines a dictionary containing lists of fruits and vegetables, sorts them alphabetically,
and prints the updated dictionary.
Key Concepts Used:
1. Dictionary (my_dict) – Stores categorized data using key-value pairs. The keys "Fruits" and
"Veggies" each hold a list of respective items, making data retrieval efficient.
2. List Data Structure (["banana", "apple", "pineapple", "custardapple"]) – Each key in
the dictionary stores a list of items. Lists allow flexible modifications, such as sorting,
appending, or removing elements.
3. Sorting Lists (sort()) – The sort() method arranges elements in ascending order. This
operation modifies the original list in place, ensuring that the elements are ordered
alphabetically.
4. Dictionary Key Access (my_dict["Fruits"] and my_dict["Veggies"]) – Retrieves the
corresponding list using its key. This allows applying list operations directly to specific
dictionary values.
5. Printing (print(my_dict)) – Displays the dictionary after sorting. The sorted lists within the
dictionary provide a structured and readable format for output.
This program efficiently organizes and sorts categorized data within a dictionary, demonstrating how
to manipulate nested lists within a dictionary.
SOURCE CODE:
my_dict={"Fruits":["banana","apple","pineapple","custardapple"],
"Veggies":["tomato","onion","potato"]}
my_dict["Fruits"].sort()
my_dict["Veggies"].sort()
print(my_dict)
OUTPUT:
{'Fruits': ['apple', 'banana', 'custard apple', 'pineapple'],
'Veggies': ['onion', 'potato', 'tomato']}
PROGRAM-10
AIM: Write a python script to iterate over dictionary using for loop
DESCRIPTION:
This program defines a dictionary containing personal details and iterates through its key-value pairs
to print them.
Key Concepts Used:
1. Dictionary (my_dict) – Stores related data as key-value pairs. Here, "Name:", "Age:", and
"Address:" serve as keys, each associated with a corresponding value.
2. Key-Value Pair Storage – Each entry in the dictionary consists of a key (e.g., "Name:") and
a value (e.g., "Amrutha"). Dictionaries provide efficient retrieval and storage of data.
3. Looping Through a Dictionary (for key, value in my_dict.items()) – The .items() method
returns key-value pairs, allowing iteration over both simultaneously. This makes accessing
and displaying dictionary elements straightforward.
4. Printing (print(key, value)) – Displays each key along with its corresponding value in a
structured format. This ensures clear representation of stored data.
This program efficiently retrieves and prints dictionary contents, demonstrating how to access and
iterate through key-value pairs.
SOURCE CODE:
my_dict={"Name:":"Amrutha","Age:":25,"Address:":"Visakhapatnam"}
for key,value in my_dict.items():
print(key,value)
OUTPUT:
Name: Amrutha
Age: 25
Address: Visakhapatnam
PROGRAM-11
AIM: Write a python script to generate a dictionary contain a number ( 1 to n) in the form (X,X*X)
using dictionary comprehension
DESCRIPTION:
This program generates a dictionary where each key is a number from 1 to the given input, and its
value is the square of that number.
Key Concepts Used:
1. User Input (input()) – Accepts an integer num from the user, determining the range for
generating squares. The input is converted to an integer using int() for numerical operations.
2. Dictionary Comprehension ({x: x*x for x in range(1, num+1)}) – Creates a dictionary
dynamically by iterating over a range of numbers. Each number x becomes a key, and its
square (x*x) becomes the corresponding value.
3. Range (range(1, num+1)) – Generates numbers from 1 to num, ensuring that all numbers
within the specified range are included in the dictionary. The +1 ensures the upper bound is
included.
4. Dictionary Storage (square) – Stores the squared values in a dictionary for efficient lookup.
Dictionaries allow quick retrieval of squared values using their keys.
5. Printing (print(square)) – Displays the dictionary, showing numbers as keys and their
squared values as values. This provides a structured representation of the computed squares.
This program efficiently creates and displays a dictionary of squared values using dictionary
comprehension, making it both concise and readable.
SOURCE CODE:
num=int(input("Enter a number:"))
square={x:x*x for x in range (1,num+1)}
print(square)
OUTPUT:
Enter a number: 8
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
PROGRAM-12
AIM: Write a python script to merge two dictionaries
DESCRIPTION:
This program merges two dictionaries using dictionary unpacking (**) and prints the combined
dictionary.
Key Concepts Used:
1. Dictionary (my_dict1 and my_dict2) – Stores key-value pairs. my_dict1 contains a name
and age, while my_dict2 holds phone number and address details. Dictionaries allow efficient
data storage and retrieval.
2. Dictionary Unpacking ({**my_dict1, **my_dict2}) – Merges multiple dictionaries into
one. The ** operator expands the key-value pairs from each dictionary and combines them
into a new dictionary.
3. Handling Key Conflicts – If both dictionaries contain the same key, the value from the
second dictionary (my_dict2) will overwrite the value from the first (my_dict1). This ensures
the latest values are retained.
4. Printing (print()) – Displays the merged dictionary in a structured format. The resulting
dictionary contains all key-value pairs from both input dictionaries.
This program efficiently merges multiple dictionaries using dictionary unpacking, making it a
concise and effective approach for combining key-value pairs.
SOURCE CODE:
my_dict1={1:"Amrutha","Age:":25}
my_dict2={"phno:":9685554425,"Address:":"Visakhapatnam"}
print("Merged Dictionaries:",{**my_dict1,**my_dict2})
OUTPUT:
Merged Dictionaries: {1: 'Amrutha', 'Age:': 25, 'phno:': 9685554425,
'Address:': 'Visakhapatnam'}
PROGRAM-13
AIM: Write a python script to map two lists into dictionary
DESCRIPTION:
This program maps two lists—one containing keys and the other containing values—into a
dictionary using the zip() function.
Key Concepts Used:
1. Lists (keys and values) – Stores related data separately. The keys list contains dictionary
keys, while the values list holds corresponding values. Lists allow easy modification and
iteration.
2. zip() Function (zip(keys, values)) – Pairs elements from both lists, creating key-value pairs.
It ensures that the first element of keys maps to the first element of values, and so on.
3. Dictionary Creation (dict(zip(keys, values))) – Converts the zipped key-value pairs into a
dictionary. This method provides a simple way to map lists into a structured key-value
format.
4. Printing (print()) – Displays the created dictionary in a readable format. The output helps
verify that the lists were successfully mapped.
This program efficiently transforms two separate lists into a dictionary, making it useful for
structuring related data.
SOURCE CODE:
keys=["name","roll no","branch","section"]
values=['ramu',12005,'IT',3]
print("mapped_dictionary is :", dict(zip(keys,values)))
OUTPUT:
mapped_dictionary is : {'name': 'ramu', 'roll no': 12005, 'branch': 'IT', 'section': 3}
PROGRAM-14
AIM: Write a python program to combine values in a list of dictionaries
DESCRIPTION:
This program combines multiple dictionaries containing item names and their quantities, summing
up quantities for duplicate items using defaultdict.
Key Concepts Used:
1. List of Dictionaries (dicts) – Stores multiple dictionaries where each dictionary represents
an item and its corresponding quantity. This structure allows easy iteration and data
aggregation.
2. defaultdict(int) – Initializes an empty dictionary where missing keys default to 0. This
prevents KeyError while updating values and simplifies summing up quantities for duplicate
items.
3. Looping Through Dictionaries (for d in dicts) – Iterates through each dictionary in the list.
This allows processing of all items dynamically without manually handling each entry.
4. Summing Values (Combined_dictionary[d["item"]] += d["quantity"]) – Adds the
quantity of each item to its corresponding key in Combined_dictionary. If an item appears
multiple times, its quantities are summed automatically.
5. Dictionary Conversion (dict(Combined_dictionary)) – Converts defaultdict into a regular
dictionary before printing. This ensures standard dictionary representation without defaultdict
behavior.
6. Printing (print()) – Displays the final combined dictionary, showing unique items with their
total quantities. This provides a structured view of aggregated data.
This program efficiently consolidates duplicate keys and sums their values, making it ideal for
inventory management or data aggregation tasks.
SOURCE CODE:
from collections import defaultdict
dicts=[{"item":"apple","quantity": 5},{"item":"banana","quantity": 15},{"item":"apple","quantity":
8},]
Combined_dictionary= defaultdict(int)
for d in dicts:
Combined_dictionary[d["item"]]+=d["quantity"]
print("Combined_dictionary:" , dict(Combined_dictionary))
OUTPUT:
Combined_dictionary: {'apple': 13, 'banana': 15}
PROGRAM-15
AIM: Write a python script to drop empty items from given dictionary
DESCRIPTION:
This program removes dictionary entries with empty or falsy values, keeping only meaningful data.
Key Concepts Used:
1. Dictionary (my_dict) – Stores key-value pairs where some values are empty (''), None,
empty lists ([]), zero (0), or False. These are considered falsy values in Python.
2. Dictionary Comprehension ({key: value for key, value in input_dict.items() if value}) –
Iterates over dictionary items and retains only those with truthy values. Falsy values like
None, '', 0, [], and False are automatically excluded.
3. items() Method (input_dict.items()) – Returns key-value pairs from the dictionary, allowing
iteration over all elements efficiently.
4. Truthy and Falsy Values – In Python, values like None, False, 0, '', and empty collections
([], {}, set()) are considered falsy. The condition if value filters them out.
5. Printing (print(cleaned_dict)) – Displays the cleaned dictionary with only truthy values,
providing a filtered version of the original data.
This program efficiently removes unwanted empty values from a dictionary, making it useful for data
cleaning and preprocessing.
SOURCE CODE:
def drop_empty_items(input_dict):
return {key:value for key,value in input_dict.items() if value}
my_dict={'a':1,'b':'','c':None ,'d':[],'e':0,'f':[1,2,3],'g':False}
cleaned_dict=drop_empty_items(my_dict)
print("cleaned_dictionary is :", cleaned_dict)
OUTPUT:
cleaned_dictionary is : {'a': 1, 'f': [1, 2, 3]}
WEEK- 2 Python Programs on Searching and Sorting
PROGRAM-1
AIM: Write a python script to sort a list using recursive insertion sort.
DESCRIPTION:
This program implements recursive insertion sort, sorting elements recursively before placing the
last element correctly.
Key Concepts Used:
 Recursive Function (insertion_sort_recursive())–Calls itself until only one element
remains.
 Base Condition (if n == 1) – Stops recursion when the array has one element.
 Sorting in Recursive Steps – Sorts n-1 elements first, then places the last one correctly.
 Insertion Step (while j >= 0 and arr[j] > last) – Moves elements forward if greater than
last.
 Handling User Input (list(map(int, input().split()))) :Reads space-separated integers as a
list.

 Efficiency: Runs in O(n²) time (like iterative insertion sort) with O(n) space due torecursion

SOURCE CODE:
def insertion_sort_recursive(arr,n=None):
if n is None:
n=len(arr)
if n==1:
return
insertion_sort_recursive(arr,n-1)
last=arr[n-1]
j=n-2
while j>=0 and arr[j]>last:
arr[j+1]=arr[j]
j-=1
arr[j+1]=last
arr=list(map(int,input("Enter the element of the array(space_seperated:)").split()))
insertion_sort_recursive(arr)
print("sorted array:",arr)
OUTPUT:
Enter the element of the array(space_seperated:) 2 7 8 9
sorted array: [2, 7, 8, 9]
PROGRAM-2
AIM: Write a python script to sort a list using recursive bubble sort
DESCRIPTION:
This program sorts a list using recursive bubble sort, where the largest element moves to its correct
position in each recursive call.
Key Concepts Used:
 Recursive Function (bubble_sort_recursive()) – Recursively sorts the array by swapping
adjacent elements.
 Base Condition (if n == 1) – Stops recursion when only one element remains.
 Swapping (if arr[i] > arr[i+1]) – Moves larger elements towards the end.
 Sorting Step (bubble_sort_recursive(arr, n-1)) – Recursively sorts the first n-1 elements.
 User Input (list(map(int, input().split()))) – Reads space-separated integers as an array.
 Time Complexity (O(n^2)) – Similar to iterative Bubble Sort.
 Space Complexity (O(n)) – Due to recursive function calls.
 Efficiency – Suitable for small datasets but inefficient for large inputs.
 Alternative Sorting – Merge Sort and Quick Sort are preferred for better efficiency.
SOURCE CODE:
def bubble_sort_recursive(arr,n=None):
if n is None:
n=len(arr)
if n==1:
return
for i in range(n-1):
if(arr[i]>arr[i+1]):
arr[i],arr[i+1]=arr[i+1],arr[i]
bubble_sort_recursive(arr,n-1)
arr=list(map(int,input("Enter the elements of the array(space_seperated:)").split()))
bubble_sort_recursive(arr)
print("sorted array:",arr)
OUTPUT:
Enter the elements of the array(space_seperated:) 48 23 44 21
sorted array: [21, 23, 44, 48]
PROGRAM-3
AIM: Write a python script to sort a list using recursive merge sort
DESCRIPTION:
This program sorts a list using recursive merge sort, a divide-and-conquer algorithm that splits the
list into smaller parts and merges them in sorted order.
Key Concepts Used:
 Recursive Function (merge_sort()) – Recursively divides the array into halves until only
single elements remain.
 Base Condition (if len(arr) <= 1) – Stops recursion when an array has one or zero elements,
as they are inherently sorted.
 Dividing the Array (left_half, right_half) – Splits the array into two halves and recursively
sorts them.
 Merging (merge(left, right)) – Combines two sorted halves into a single sorted array.
 Comparison (if left[i] < right[j]) – Compares elements and appends the smaller one first to
maintain order.
 Handling Remaining Elements (while i < len(left) / while j < len(right)) – Ensures no
elements are left behind after merging.
 Handling User Input (list(map(int, input().split()))) – Reads space-separated integers and
converts them into a list.
 Time Complexity (O(n log n)) – Efficient for large datasets due to repeated halving and
merging.
 Space Complexity (O(n)) – Uses extra space for merging, unlike in-place sorting algorithms.
This method provides an efficient and widely used approach to sorting, making it faster than Bubble
and Insertion Sort.
SOURCE CODE:
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return merge(left_half, right_half)
def merge(left, right):
sorted_arr = []
i=j=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
sorted_arr.append(left[i])
i += 1
else:
sorted_arr.append(right[j])
j += 1
while i < len(left):
sorted_arr.append(left[i])
i += 1
while j < len(right):
sorted_arr.append(right[j])
j += 1
return sorted_arr
arr = list(map(int, input("Enter the elements of the array (space-separated): ").split()))
sorted_arr = merge_sort(arr)
print("Sorted array:", sorted_arr)
OUTPUT:
Enter the elements of the array (space-separated): 12 56 45 78 15
Sorted array: [12, 15, 45, 56, 78]

PROGRAM-4
AIM: Write a python script to sort a list using recursive quick sort
DESCRIPTION:
This program sorts a list using recursive quick sort, a divide-and-conquer algorithm that partitions
elements around a pivot.
 Recursive Function (quick_sort()) – Recursively sorts subarrays based on the pivot.
 Base Condition (if len(arr) <= 1) – Stops recursion when the array is already sorted.
 Choosing Pivot (pivot = arr[-1]) – Selects the last element as the pivot.
 Partitioning (left and right) – Splits elements into smaller (left) and greater (right) lists.
 Recursive Sorting (quick_sort(left) + [pivot] + quick_sort(right)) – Sorts partitions and
merges with the pivot.
 Handling User Input (list(map(int, input().split()))) – Reads space-separated integers into a
list.
 Time Complexity (O(n log n)) – Efficient but degrades to O(n²) in the worst case.
 Space Complexity (O(n)) – Uses extra space for recursive calls and partitioning.
This method is efficient and widely used due to its in-place sorting capability with minor
modifications.
SOURCE CODE:
def quick_sort(arr):
if len(arr)<=1:
return arr
pivot=arr[-1]
left=[x for x in arr[:-1] if x <=pivot]
right=[x for x in arr[:-1] if x>pivot]
return quick_sort(left)+[pivot]+quick_sort(right)
arr=list(map(int,input("Enter the elements of the array(space_seperated):").split()))
sorted_arr=quick_sort(arr)
print("sorted array:",sorted_arr)
OUTPUT:
Enter the elements of the array(space_seperated): 12 25 48 65 11 8 16 56
sorted array: [8, 11, 12, 16, 25, 48, 56, 65]
PROGRAM-5
AIM: Write a python script to search an element using recursive linear search
DESCRIPTION:
This program searches for an element using recursive linear search, a straightforward method that
checks elements sequentially.
 Recursive Function (linear_search()) – Searches the list by checking one element at a time.
 Base Condition (if index >= len(arr)) – Stops recursion when all elements are checked.
 Comparison (if arr[index] == target) – Returns the index if the target is found.
 Recursive Call (linear_search(arr, target, index + 1)) – Moves to the next element if the
target is not found.
 Handling User Input (list(map(int, input().split()))) – Reads space-separated integers into a
list.
 Time Complexity (O(n)) – Checks each element sequentially in the worst case.
 Space Complexity (O(n)) – Uses additional stack space due to recursive calls.
This method is useful for unsorted lists but is inefficient compared to binary search for sorted data.
SOURCE CODE:
def linear_search(arr,target,index=0):
if index >= len(arr):
return -1
if arr[index] == target:
return index
return linear_search(arr, target, index + 1)
arr = list(map(int, input("Enter the elements of the array (space-separated): ").split()))
target = int(input("Enter the target element: "))
result = linear_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found in the array")
OUTPUT:
Enter the elements of the array (space-separated): 12 25 48 65 11 8 16 56
Enter the target element: 8
Element found at index 5
PROGRAM-6
AIM: Write a python script to search an element using recursive binary search
DESCRIPTION:
This program searches for an element using recursive binary search, a fast searching technique for
sorted lists.
 Recursive Function (binary_search()) – Recursively divides the list into halves to locate the
target efficiently.
 Base Condition (if low > high) – Stops recursion when the target is not found in the search
range.
 Middle Element (mid = (low + high) // 2) – Selects the midpoint of the list for comparison.
 Direct Match (if arr[mid] == target) – Returns the index immediately if the target is found
at mid.
 Left or Right Search (binary_search()) – Recursively searches in the left half if the target is
smaller, otherwise in the right half.
 Sorting Input List (arr.sort()) – Ensures the list is sorted before performing binary search
for correctness.
 Handling User Input (list(map(int, input().split()))) – Reads space-separated numbers and
converts them into a list.
 Edge Case Handling – Works even if the array has duplicate values, a single element, or is
empty.
 Time Complexity (O(log n)) – Reduces search space by half in every step, making it much
faster than linear search.
 Space Complexity (O(log n)) – Uses recursive function calls, adding log(n) stack frames in
the worst case.
 Practical Use Cases – Commonly used in large datasets, searching in sorted databases, and
optimized lookup operations.
 Comparison with Iterative Binary Search – Recursive binary search uses extra space due
to recursion, whereas iterative binary search operates in O(1) space.
 Binary Search on Unsorted Data – If performed on an unsorted list, the results are
unpredictable, highlighting the importance of sorting first.
 Binary Search on Large Data – Suitable for massive datasets where linear search would be
too slow.
 Best Case Complexity (O(1)) – If the middle element is the target, it is found in the first
step.
 Worst Case Complexity (O(log n)) – The search continues until only one element is left,
requiring log(n) steps.
This method is significantly more efficient than linear search, making it ideal for large sorted
datasets.
SOURCE CODE:
def binary_search(arr, target, low, high):
if low > high:
return -1
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif target < arr[mid]:
return binary_search(arr, target, low, mid - 1)
else:
return binary_search(arr, target, mid + 1, high)
arr = list(map(int, input("Enter the unsorted elements of the array (space-separated): ").split()))
target = int(input("Enter the target element: "))
arr.sort()
result = binary_search(arr, target, 0, len(arr) - 1)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found in the array")
OUTPUT:
Enter the unsorted elements of the array (space-separated): 12 25 48 65 11 8 16 56
Enter the target element: 45
Element not found in the array
PROGRAM-7
AIM: Write a python script to search an element using recursive Fibonacci search
DESCRIPTION:
This program searches for an element using recursive Fibonacci search, an efficient technique for
sorted arrays based on Fibonacci numbers.
 Fibonacci Number Generation (fib_gen(n)) – Computes Fibonacci numbers until reaching
or exceeding the array size to determine search intervals.
 Recursive Function (fibonacci_search()) – Uses Fibonacci numbers to divide the array and
recursively search for the target element.
 Base Condition (if fib_m1 and arr[offset + 1] == target) – Stops recursion when the target
is found at the last checked index.
 Middle Element (i = min(offset + fib_m2, len(arr) - 1)) – Determines the search position
using Fibonacci numbers, similar to binary search.
 Left or Right Search Decision – Moves the search left if the middle element is greater than
the target, otherwise shifts right.
 Sorting Input List (arr.sort()) – Ensures that the array is sorted before performing Fibonacci
search, a necessary condition.
 Handling User Input (list(map(int, input().split()))) – Reads space-separated numbers from
the user and converts them into a list for processing.
 Time Complexity (O(log n)) – Comparable to binary search but often requires fewer
comparisons, making it more efficient in certain cases.
 Space Complexity (O(1)) – Operates in constant space, unlike recursive binary search,
which consumes additional memory for function calls.
 Less Arithmetic Operations – Unlike binary search, which repeatedly divides by 2,
Fibonacci search uses addition and subtraction, which can be computationally cheaper.
 Advantage Over Binary Search – Particularly useful in environments where division is
expensive, such as embedded systems and hardware-based computations.
 Application in Large Datasets – Effective for searching in large, sorted datasets where
computational efficiency is crucial.
 Practical Use Cases – Commonly used in databases, numerical computing, and specialized
search problems involving sorted lists.
This method provides a powerful alternative to binary search, leveraging Fibonacci numbers to
optimize search efficiency.
SOURCE CODE:
def fib_gen(n):
fib_m2, fib_m1 = 0, 1
fib_m = fib_m2 + fib_m1
while fib_m < n:
fib_m2, fib_m1 = fib_m1, fib_m
fib_m = fib_m2 + fib_m1
return fib_m2, fib_m1, fib_m
def fibonacci_search(arr, target, offset, fib_m2, fib_m1, fib_m):
while fib_m > 1:
i = min(offset + fib_m2, len(arr) - 1)
if arr[i] < target:
fib_m, fib_m1, fib_m2 = fib_m1, fib_m2, fib_m - fib_m1
offset = i
elif arr[i] > target:
fib_m, fib_m1, fib_m2 = fib_m2, fib_m1 - fib_m2, fib_m - fib_m1
else:
return i
if fib_m1 and offset + 1 < len(arr) and arr[offset + 1] == target:
return offset + 1
return -1
arr = list(map(int, input("Enter the unsorted elements of the array (space-separated): ").split()))
target = int(input("Enter the target element: "))
arr.sort()
print("Sorted array:", arr)
fib_m2, fib_m1, fib_m = fib_gen(len(arr))
result = fibonacci_search(arr, target, -1, fib_m2, fib_m1, fib_m)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found in the array")
OUTPUT:
Enter the unsorted elements of the array (space-separated): 12 25 48 65 11 8 16 56
Enter the target element: 8
Sorted array: [8, 11, 12, 16, 25, 48, 56, 65]
Element found at index 0
WEEK-3 Python Programs on Text Handling
PROGRAM-1
AIM: Write a python script that asks the user for a large integer and inserts commas into it according
to the standard American convention for commas in large numbers. For instance, if the user enters
1000000, the output should be 1,000,000
DESCRIPTION:
This program formats a large number with commas as thousand separators to improve readability.
Key Concepts Used:
1. User Input (input()) – Takes a long number as input from the user. The int() function ensures
the input is treated as a numerical value.
2. String Formatting ("{:,}".format(number)) – Uses Python’s string formatting feature to
insert commas at thousand places automatically. This makes large numbers easier to read.
3. Comma as a Thousand Separator (:,) – The , inside the format string specifies that commas
should be added every three digits from the right, following standard numeric formatting
rules.
4. Printing (print()) – Displays the formatted number with commas, ensuring better clarity for
users when dealing with large numbers.
This program is useful for improving numerical readability, particularly in financial and statistical
applications.
SOURCE CODE:
number=int(input("Enter a long number:"))
print("{:,}".format(number))
OUTPUT:
Enter a long number: 83476680
83,476,680
PROGRAM-2
AIM: Write a python script that asks the user to enter two strings of the same length. The program
should then check to see if the strings are of the same length. If they are not, the program should
print an appropriate message and exit. If they are of the same length, the program should alternate
the characters of the two strings. For example, if the user enters abcde and ABCDE the program
should print out AaBbCcDdEe.
DESCRIPTION:
This program takes two strings of the same length and merges them by alternating their characters.
1. User Input (input()) – Accepts two strings from the user. The inputs are stored in str1 and
str2.
2. String Length Check (len()) – Uses len(str1) and len(str2) to determine the lengths of both
strings. If the lengths are unequal, the program prints an error message and exits.
3. String Concatenation (str3 = str3 + (str2[i] + str1[i])) – Constructs a new string by taking
characters alternately from str2 and str1. The result is built dynamically using a loop.
4. Looping Through Indices (for i in range(l1)) – Iterates over the indices of the input strings,
ensuring all characters are processed in order.
5. Printing (print()) – Displays the final merged string, where characters from both inputs are
interleaved.
SOURCE CODE:
print("Enter two strings of same length")
str1=input("Enter string 1")
str2=input("Enter string 2")
l1=len(str1)
l2=len(str2)
if(l1!=l2):
print("The strings are not of equal length")
else:
str3=''
for i in range(l1):
str3=str3+(str2[i]+str1[i])
print("The resultant string is",str3)
OUTPUT:
Enter two strings of same length
Enter string 1 LEARN
Enter string 2 TECH. The strings are not of equal length
PROGRAM-3
AIM: Write a python script in algebraic expressions, the symbol for multiplication is often left out,
as in 3x+4y or 3(x+5). Computers prefer those expressions to include the multiplication symbol, like
3x+4y or 3*(x+5).Write a program that asks the user for an algebraic expression and then inserts
multiplication symbols where appropriate.
DESCRIPTION:
This program adds missing multiplication signs in an algebraic expression.
Key Concepts Used:
1. User Input (input()) – Reads an algebraic expression as a string.
2. Loop (while i < len(l)) – Iterates through characters to modify the expression.
3. Handling Parentheses – Ensures multiplication before expressions inside parentheses.
4. Detecting Variables – Adds * before standalone variables for clarity.
5. String Construction – Builds and prints the corrected expression.
SOURCE CODE:
s=input("Enter algebraic expression")
l=list(s)
res=' '
i=0
while(i<len(l)):
if(l[i]=='('):
index=l.index(')')
s2=' '.join(l[i:index+1])
res=res+'*'+s2
i=i+len(s2)
elif(l[i].isalpha()):
res=res+'*'+l[i]
i=i+1
else:
res=res+l[i]
i=i+1
print(res)
OUTPUT:
Enter algebraic expression 4X+7Z as 4*X+7*Z
PROGRAM-4
AIM: Write a python script to remove characters that have odd index values in a given string.
DESCRIPTION:
This program removes characters at odd indices from a given string and returns a modified version
with only even-indexed characters.
Key Concepts Used:
1. User Input (input()) – Accepts a string from the user and stores it for processing. This allows
dynamic modification of any given text.
2. enumerate() Function (enumerate(input_string)) – Assigns an index to each character,
making it easier to track positions in the string while iterating.
3. List Comprehension ([char for i, char in enumerate(input_string) if i % 2 == 0]) –
Iterates through the string and filters out characters with odd indices. The condition i % 2 ==
0 ensures only even-indexed characters are retained.
4. String Joining (' '.join(...)) – Converts the filtered list of characters back into a string with
spaces between them, making the output more readable.
5. Printing (print(result)) – Displays the final string with characters from odd positions
removed, ensuring clarity in output presentation.
This program is useful for string manipulation tasks, such as encoding messages or modifying text-
based data efficiently.
SOURCE CODE:
def remove_odd(input_string):
return ' '.join([char for i, char in enumerate (input_string) if i % 2 == 0])
user_input=input("Enter a string:")
result=remove_odd(user_input)
print("Result", result)
OUTPUT:
Enter a string: ENGINEERING
Result E G N E I G
PROGRAM-5
AIM: Write a python script to count the number of occurrence of each word in a given sentence
DESCRIPTION:
This program counts the occurrences of each word in a given sentence, ignoring case differences.
Key Concepts Used:
1. User Input (input()) – Reads a sentence from the user and stores it for processing. This
allows dynamic word frequency analysis.
2. Lowercasing and Splitting (sentence.lower().split()) – Converts the sentence to lowercase
to ensure case insensitivity, then splits it into individual words.
3. Dictionary for Counting (word_count = {}) – Uses a dictionary to store words as keys and
their occurrences as values, making lookup and updates efficient.
4. Loop (for word in words) – Iterates through the list of words and updates their count in the
dictionary. If a word exists, its count increases; otherwise, it is added with an initial count of
1.
5. Printing (print(result)) – Displays the word occurrences in dictionary format, showing the
frequency of each word in the input sentence.
This program efficiently analyzes word frequency, making it useful for text processing and natural
language applications.
SOURCE CODE:
def count_word(sentence):
words=sentence.lower().split()
word_count= {}
for word in words:
if word in word_count:
word_count[word]+=1
else:
word_count[word]=1
return word_count
user_input=input("Enter a Sentence:")
result=count_word(user_input)
print("WORD OCCURANCES:", result)
OUTPUT:
Enter a Sentence: To count the number of occurrence of each word in a given sentence
WORD OCCURANCES: {'to': 1, 'count': 1, 'the': 1, 'number': 1, 'of': 2, 'occurrence': 1, 'each': 1,
'word': 1, 'in': 1, 'a': 1, 'given': 1, 'sentence': 1}
PROGRAM-6
AIM: Write a python script that accepts input String and Displays that input back in Lower case and
Upper case
DESCRIPTION:
This program converts a given string into both uppercase and lowercase formats to standardize text
representation.
Key Concepts Used:
1. User Input (input()) – Accepts a string from the user, allowing flexible text processing.
2. Function Definition (display_cases(input_string)) – Uses a function to encapsulate the
logic for case conversion, making the code reusable.
3. Uppercase Conversion (upper()) – Converts all characters in the input string to uppercase,
ensuring uniform capitalization.
4. Lowercase Conversion (lower()) – Converts all characters to lowercase, useful for case-
insensitive comparisons.
5. Printing Output (print()) – Displays both uppercase and lowercase versions of the given
string, making it easy to analyze case transformations.
This program is useful in text formatting, data preprocessing, and case normalization in applications
like search engines or user input validation.
SOURCE CODE:
def display_cases(input_string):
print("Uppercase:", input_string.upper())
print("Lowercase:", input_string.lower())
user_input=input("Enter a String:")
display_cases(user_input)
OUTPUT:
Enter a String: Accepts input String and Displays that input back in Lower case and Upper case
Uppercase: ACCEPTS INPUT STRING AND DISPLAYS THAT INPUT BACK IN LOWER CASE
AND UPPER CASE
Lowercase: accepts input string and displays that input back in lower case and upper case
PROGRAM-7
AIM: Write a python script to reverse a string
DESCRIPTION:
This program reverses a given string using slicing and returns the modified string.
Key Concepts Used:
1. User Input (input()) – Accepts a string from the user, allowing dynamic input processing.
2. Function Definition (rev_string()) – Wraps the logic inside a function for modularity and
reusability.
3. String Slicing ([::-1]) – Efficiently reverses the string by stepping through it from the last
character to the first. This approach is faster than loops.
4. Returning the Result (return input_string[::-1]) – Instead of directly printing, the function
returns the reversed string, allowing flexibility in further processing.
5. No Explicit Printing – The function is called but not printed, meaning the reversed string
won’t be displayed unless explicitly printed using print(rev_string(user_input)).
This program is useful in applications like checking for palindromes, cryptography, and text
formatting.
SOURCE CODE:
def rev_string(input_string):
return input_string[::-1]
user_input=input("Enter a String:")
rev_string(user_input)
OUTPUT:
Enter a String: ENGINEERING
'GNIREENIGNE'
PROGRAM-8
AIM: Write a python script to check whether a string ends with a specified characters
DESCRIPTION:
This program checks whether a given string ends with a specified substring.
Key Concepts Used:
1. User Input (input()) – Accepts a main string and a substring to check for at the end.
2. Function Definition (end_check()) – Encapsulates the logic to check if a string ends with
the given substring, improving reusability.
3. String Method (endswith()) – Uses Python’s built-in endswith() function to efficiently
determine if the string ends with the given input.
4. Conditional Statement (if-else) – Compares the function’s output and prints whether the
condition is met.
5. Printing Output (print()) – Displays a user-friendly message indicating whether the string
ends with the specified substring.
This program is useful in text validation, URL verification, and file format checking.
SOURCE CODE:
def end_check(input_string, ending):
return input_string.endswith(ending)
user_input=input("Enter a String:")
ending=input("Enter ending of String:")
if end_check(user_input, ending):
print( user_input, "ends with", ending)
else:
print( user_input, "does not ends with", ending)
OUTPUT:
Enter a String: ENGINEERING
Enter ending of String: ING
ENGINEERING ends with ING
PROGRAM-9
AIM: Write a python script for lambda as an argument to a higher-order function
DESCRIPTION:
This program demonstrates the use of anonymous functions, also known as lambda functions. Unlike
regular functions defined using def, lambda functions are single-line functions without a name. They
are useful for short operations where defining a full function is unnecessary.
Lambda Function Definition
The program defines a lambda function named double using the syntax lambda x: x * 2. This
function takes a single argument x and returns x multiplied by 2.
Execution and Output
The function is then called with the value 5, meaning double(5) results in 10. The program prints the
output, showing how lambda functions can be used to perform quick calculations without requiring
multiple lines of code.
Key Concepts Used:
1. Lambda Function (lambda x: x * 2) – Defines an anonymous function that takes a single
argument and returns its double. Lambda functions are useful for short, one-time operations.
2. Function Call (double(5)) – Calls the lambda function with 5 as input, multiplying it by 2
and returning 10.
3. Printing Output (print()) – Displays the computed result, making the program interactive.
4. Concise Function Definition – A lambda function allows defining simple logic in a single
line, improving readability and avoiding the need for a separate function definition.
5. Use Case – Lambda functions are useful in functional programming, quick calculations, and
when passing functions as arguments.
SOURCE CODE:
double = lambda x: x * 2
print(double(5))
OUTPUT:
10
PROGRAM-10
AIM: Write a python script for filter()- creates a list of elements for which a function returns true
filter resembles a for loop but it is a built in function and faster
DESCRIPTION:
This program extracts even numbers from a list using a lambda function and filter().
Key Concepts Used:
1. List Definition (my_list) – A predefined list of integers is used as input for filtering,
containing both even and odd numbers.
2. Lambda Function (lambda x: (x % 2 == 0)) – An anonymous function checks whether
each element is divisible by 2, returning True for even numbers and False for odd ones.
3. Filter Function (filter()) – Iterates over my_list, applying the lambda function to retain only
numbers that satisfy the even condition. The result is a filter object (an iterator).
4. Type Conversion (list()) – Since filter() returns an iterator, list() is used to convert it into a
list, making it easy to store and print.
5. Printing Output (print(new_list)) – Displays the final list of even numbers extracted from
my_list.
This program is useful in scenarios requiring filtering of elements based on specific conditions, such
as data preprocessing, number categorization, and functional programming.
SOURCE CODE:
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
OUTPUT:
[4, 6, 8, 12]
PROGRAM-11
AIM: Write a python script for map() - applies a function to all the items in an input_list
map(function_to_apply, list_of_inputs)
DESCRIPTION:
This program checks whether each number in a given range is negative and returns a list of Boolean
values.
Key Concepts Used:
1. Range Function (range(-5, 5)) – Generates a sequence of numbers from -5 to 4, providing a
mix of negative, zero, and positive values.
2. Lambda Function (lambda x: x < 0) – Defines an anonymous function that checks if a
number is less than zero, returning True for negative numbers and False otherwise.
3. Map Function (map()) – Applies the lambda function to each element of number_list,
creating an iterator that stores the Boolean results (True for negative numbers, False for non-
negative numbers).
4. Type Conversion (list()) – Converts the map object (an iterator) into a list, making the output
easy to print and use.
5. Printing Output (print(less_than_zero)) – Displays a list of Boolean values indicating
whether each corresponding number in number_list is negative.
This program is useful for boolean masking, data filtering, and logical operations in data analysis.
SOURCE CODE:
number_list = range(-5, 5)
less_than_zero = list(map(lambda x: x < 0, number_list))
print(less_than_zero)
OUTPUT:
[True, True, True, True, True, False, False, False, False, False]
PROGRAM-12
AIM: Write a python script to generate a new list containing the square of each number from an
existing list
DESCRIPTION:
This program calculates the square of each element in a list using a for loop and stores the results in a
new list.
Key Concepts Used:
1. List Definition (items) – A predefined list contains numbers [1, 2, 3, 4, 5], serving as input
for squaring.
2. Looping (for i in items) – Iterates through each number in items, ensuring that every element
is processed.
3. Exponentiation (i**2) – Computes the square of the current element using the
exponentiation operator (**).
4. List Append (squared.append(i**2)) – Stores the squared value in a new list squared,
dynamically building it during iteration.
5. Printing Output (print(squared)) – Displays the final list containing the squared values of
items.
This program is useful for mathematical computations, data transformations, and preparing datasets
for machine learning.
SOURCE CODE:
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
print(squared)
OUTPUT:
[1, 4, 9, 16, 25]
PROGRAM-13
AIM: Write a python script which having of a list of inputs, instead we can even have a list of
functions
DESCRIPTION:
This program applies two functions, multiply and add, to numbers from 0 to 4 using map().
Key Concepts Used:
1. Function Definitions (multiply() and add()) – multiply() squares a number, and add()
doubles it, providing two distinct transformations.
2. Function List (funcs = [multiply, add]) – Stores multiple functions in a list, allowing
dynamic application to numbers.
3. Looping (for i in range(5)) – Iterates through numbers from 0 to 4, applying both functions
to each number.
4. Lambda with map() (map(lambda x: x(i), funcs)) – Iterates over the function list, applying
each function to i, generating transformed values.
5. Printing Output (print(value)) – Displays the results as a list where each number undergoes
both transformations.
This approach is useful in functional programming, allowing dynamic function application for
mathematical operations and data processing.
SOURCE CODE:
def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = list(map(lambda x: x(i), funcs))
print(value)
OUTPUT:
[0, 0]
[1, 2]
[4, 4]
[9, 6]
[16, 8]
PROGRAM-14
AIM: Write a python script for higher order function reduce()
DESCRIPTION:
This program calculates the mean (average) of a list using the reduce() function from the functools
module.
Key Concepts Used:
1. Importing reduce() (from functools import reduce) – reduce() is used to apply a function
cumulatively to the elements of a list, simplifying summation.
2. Lambda Function (lambda x, y: x + y) – Defines an anonymous function that takes two
numbers and returns their sum, allowing cumulative addition of list elements.
3. Using reduce() (reduce((lambda x, y: x + y), l)) – Iterates through the list, applying the
lambda function to accumulate the sum of all elements.
4. Mean Calculation (mean = float(sumoflist) / len(l)) – Computes the mean by dividing the
total sum by the number of elements, ensuring a floating-point result.
5. Function Call (cal_mean(l)) – Calls the function with l = [1,2,3,4,5], displaying the mean
value.
This program efficiently calculates the mean without explicit loops, making it useful for data analysis
and mathematical computations.
SOURCE CODE:
from functools import reduce
def cal_mean(l):
sumoflist=reduce((lambda x,y:x+y),l) #cal cumulative sum
mean=float(sumoflist)/len(l)
print(mean)
l=[1,2,3,4,5]
cal_mean(l)
OUTPUT:
3.0
PROGRAM-15
AIM: Write a python script to import math module and use some built in functions
DESCRIPTION:
This program stores built-in mathematical functions in a list and applies them dynamically.
Key Concepts Used:
1. Importing math Module (import math) – Enables access to mathematical functions like
math.sqrt(), which computes square roots.
2. Function List (funcs = [abs, math.sqrt]) – Stores functions abs() (absolute value) and
math.sqrt() (square root) in a list, allowing indexed function access.
3. Applying Functions (funcs ) – Retrieves math.sqrt from the list using index 1 and applies it
to 45, computing its square root.
4. Applying Absolute Function (funcs[0](-234)) – Retrieves abs() from the list using index 0
and applies it to -234, returning its absolute value.
5. Printing Results (print()) – Displays the function list and outputs the computed results of
math.sqrt(45) and abs(-234).
This program demonstrates function storage and dynamic execution, which is useful in functional
programming and modular code design.
SOURCE CODE:
import math
math.sqrt
funcs=[abs,math.sqrt]
print(funcs)
print("Applying math.sqrt to 45:",funcs[1](45) )
print("Applying abs to -234:",funcs[0](-234))
OUTPUT:
[<built-in function abs>, <built-in function sqrt>]
Applying math.sqrt to 45: 6.708203932499369
Applying abs to -234: 234
WEEK-5 Python Programs for calculating Mean, Mode,
Median, Variance, Standard Deviation
PROGRAM-1
AIM: Write a python script to calculate the mean using numpy library
DESCRIPTION:
The script utilizes the NumPy library to create an array and compute its mean value. The array is
defined using np.array(), but incorrect usage of parentheses instead of square brackets may cause
unintended behavior. The np.mean() function is used to calculate the arithmetic mean by summing all
elements in the array and dividing by the total count. Finally, the mean value is printed to the
console.
Key Concepts:
1. NumPy Library (numpy)
o numpy is a powerful Python library for numerical computations, particularly for
handling arrays and performing mathematical operations efficiently.
2. Creating a NumPy Array (np.array())
o The np.array() function creates an array from a list or tuple.
o Using parentheses instead of square brackets can lead to an incorrect structure.
3. Calculating Mean (np.mean())
o The np.mean() function computes the average value of all elements in the array.
o It sums all elements and divides by the total count, returning the mean.
SOURCE CODE:
import numpy as np
p=np.array([5,6,7]),([2,3,4])
print(p)
print(np.mean(p))
OUTPUT:
(array([5, 6, 7]), [2, 3, 4])
4.5
PROGRAM-2
AIM: Write a python script to calculate the median using numpy library
DESCRIPTION:
The script uses the NumPy library to create an array and calculate its median value. The array is
defined using np.array(), which stores a sequence of numerical values. The np.median() function is
then used to determine the median, which is the middle value when the numbers are arranged in
ascending order. If the number of elements is even, the median is the average of the two middle
values. Finally, the median value is printed to the console.
Key Concepts:
1. NumPy Library (numpy)
o numpy is a Python library used for numerical operations, especially for handling
arrays and mathematical functions efficiently.
2. Creating a NumPy Array (np.array())
o The np.array() function is used to create an array containing multiple numerical
values.
o This allows easy application of mathematical operations on the dataset.
3. Calculating Median (np.median())
o The np.median() function determines the middle value of a sorted array.
o If the number of elements is odd, it returns the middle element.
o If the number of elements is even, it returns the average of the two middle values.
SOURCE CODE:
import numpy as np
p=np.array([56,24,32,55,24,53])
print(p)
print("The median is:",np.median(p))
OUTPUT:
[56 24 32 55 24 53]
The median is: 42.5
PROGRAM-3
AIM: Write a python script to calculate the standard deviation using numpy library
DESCRIPTION:
The script utilizes the NumPy library to create an array and compute its standard deviation. The array
is defined using np.array(), storing multiple numerical values. The np.std() function is then used to
calculate the standard deviation, which measures the dispersion or spread of the data relative to its
mean. A lower standard deviation indicates that the data points are closer to the mean, while a higher
standard deviation signifies greater variability. Finally, the computed standard deviation is printed to
the console.
Key Concepts:
1. NumPy Library (numpy)
o numpy is a powerful Python library for numerical operations, enabling efficient
computations on arrays and mathematical functions.
2. Creating a NumPy Array (np.array())
o The np.array() function is used to create an array containing numerical values.
o This allows various mathematical operations, such as mean, median, and standard
deviation, to be performed efficiently.
3. Calculating Standard Deviation (np.std())
o The np.std() function computes the standard deviation, which quantifies how much
the data deviates from the mean.
o A low standard deviation indicates that data points are close to the mean, while a high
standard deviation suggests greater variation in the dataset.
SOURCE CODE:
import numpy as np
sd=np.array([45,56,46,24,85])
print(sd)
print("The standard deviation is:",np.std(sd))
OUTPUT:
[45 56 46 24 85]
The standard deviation is: 19.85346317396539
PROGRAM-4
AIM: Write a python script to calculate variance using numpy library
DESCRIPTION:
The script uses the NumPy library to create an array and compute its variance. The array is defined
using np.array(), which stores multiple numerical values. The np.var() function is then used to
calculate the variance, which measures the average squared deviation of each data point from the
mean. A higher variance indicates that the data points are more spread out, while a lower variance
suggests they are closer to the mean. Finally, the computed variance is printed to the console.
Key Concepts:
1. NumPy Library (numpy)
o numpy is a Python library that provides efficient handling of arrays and mathematical
operations.
o It includes statistical functions like mean, median, variance, and standard deviation.
2. Creating a NumPy Array (np.array())
o The np.array() function is used to define an array of numerical values.
o This enables fast and efficient mathematical computations on the dataset.
3. Calculating Variance (np.var())
o The np.var() function computes the variance, which represents how much the data
points deviate from the mean.
o It is calculated by taking the average of the squared differences from the mean.
o A low variance suggests that the data points are close to the mean, while a high
variance indicates greater spread.
SOURCE CODE:
import numpy as np
v=np.array([25,45,15,76,85,95])
print(v)
print("The variance is:",np.var(v))
OUTPUT:
[25 45 15 76 85 95]
The variance is: 920.1388888888888
PROGRAM-5
AIM: Write a python script to calculate average using numpy library
DESCRIPTION:
The script uses NumPy to compute both the simple and weighted average of a numerical array. The
np.average() function first calculates the arithmetic mean by summing all elements and dividing by
their count. Then, a weighted average is computed using another array of weights, where each
element’s contribution is adjusted based on its assigned weight. Finally, both average values are
printed to the console.
Key Concepts:
 NumPy Library (numpy) – A powerful library for numerical computations, particularly for
handling arrays and performing statistical operations efficiently.
 Creating a NumPy Array (np.array()) – Defines a structured dataset that enables fast and
efficient mathematical operations.
 Simple Average (np.average()) – Computes the arithmetic mean by summing all elements
and dividing by their count, providing a central value for the dataset.
 Weighted Average (np.average(a, weights=wt)) – Assigns different levels of importance to
each element based on given weights, making it useful for cases where some values
contribute more than others.
 Handling Weights in Averages – If no weights are provided, np.average() defaults to
computing a simple mean; when weights are provided, it calculates a weighted mean by
dividing the weighted sum by the sum of weights.
SOURCE CODE:
import numpy as np
a=np.array([51,95,34])
print(a)
print(np.average(a))
wt=np.array([65,48,25])
print(np.average(a,weights=wt))
OUTPUT:
[51 95 34]
60.0
63.22463768115942
PROGRAM-6
AIM: Write a python script to calculate percentile comparison using numpy library
DESCRIPTION:
The script uses NumPy to compute the percentile of a numerical array. The np.array() function is
used to define the dataset, and the np.percentile() function calculates the specified percentile. A
percentile represents the value below which a given percentage of data points fall. In this script, the
52nd percentile is determined, meaning it finds the value below which 52% of the data points lie.
The computed percentile value is then printed to the console.
Key Concepts:
 NumPy Library (numpy) – A widely used library for numerical operations, particularly for
handling arrays and performing statistical calculations efficiently.
 Creating a NumPy Array (np.array()) – Defines a structured dataset that allows fast and
efficient mathematical operations.
 Percentile Calculation (np.percentile()) – Computes the percentile value for a given
percentage, determining the data point below which that percentage of values fall.
 Understanding Percentiles – The 52nd percentile means that 52% of the data points in the
array are below the calculated value. Percentiles are commonly used in statistics to compare
data distributions.
SOURCE CODE:
import numpy as np
a=np.array([54,85,56,48])
print(a)
print("The percentile is:",np.percentile(a,52))
OUTPUT:
[54 85 56 48]
The percentile is: 55.12
PROGRAM-7
AIM: Write a python script to calculate peer to peer using numpy library
DESCRIPTION:
The script uses NumPy to compute the peer-to-peer (PTP) range, which is the difference between
the maximum and minimum values in an array. The np.array() function is used to define a numerical
dataset, but there is a syntax issue in the array definition due to incorrect parentheses usage. The
np.ptp() function then calculates the range for each column when applied along axis 0, returning the
difference between the highest and lowest values for each corresponding position in the arrays. The
computed peak-to-peak values are printed to the console.
Key Concepts:
 NumPy Library (numpy) – A powerful library for numerical computations, providing
efficient handling of arrays and mathematical operations.
 Creating a NumPy Array (np.array()) – Defines structured numerical data for performing
operations, though the array should be correctly formatted using square brackets [] instead of
incorrect parentheses.
 Peak-to-Peak Calculation (np.ptp()) – Computes the range of values by subtracting the
minimum value from the maximum in an array or along a specified axis.
 Axis Parameter in np.ptp() – Using axis=0 finds the peak-to-peak range column-wise, while
axis=1 would compute it row-wise.
SOURCE CODE:
import numpy as np
a=np.array([2,8,9]),([5,6,15])
print(np.ptp(a,0))
OUTPUT:
[3 2 6]
WEEK- 6 Python Programs for Karl Pearson
Coefficient of Correlation, Rank Correlation
PROGRAM-1
AIM: Write a python script to find out the correlation between the variables years of experience and
annual salary in following data using karl pearson’s correlation coefficient method
DESCRIPTION:
This program calculates the Pearson correlation coefficient between years of experience and annual
salary using Karl Pearson's formula.
Key Concepts Used:
1. Mathematical Computation (math.sqrt()) – The program uses mathematical operations like
summation, squaring, and square root calculations to determine correlation.
2. List Operations (sum(), zip()) – The function computes the sum of values, sum of squares,
and sum of products from two lists, years_of_emp and annual_salary.
3. Pearson Correlation Formula (r = numerator / denominator) – The formula is applied as:

where n is the number of data points, and x, y represents the variables.


 r > 0 indicates a positive correlation (as experience increases, salary increases).
 r < 0 indicates a negative correlation (as experience increases, salary decreases).
 r = 0 indicates no correlation (no relationship between variables).
4. Error Handling (if denominator == 0) – Prevents division by zero by returning 0 when the
denominator is zero.
5. Function Implementation (pearson(x, y)) – Encapsulates the correlation computation
within a function for reusability.
6. Printing Results (print(f"...")) – Displays the calculated Pearson correlation coefficient
between years of experience and salary.
This program effectively measures the linear relationship between experience and salary, helping in
statistical analysis and data science applications.
SOURCE CODE:
import math
def pearson(x,y):
n=len(x)
sum_x=sum(x)
sum_y=sum(y)
sum_xy=sum([x*y for x,y in zip (x,y)])
sum_x_square=sum([x**2 for x in x])
sum_y_square=sum([y**2 for y in y])
numerator=n*sum_xy-sum_x*sum_y
denominator=math.sqrt((n*sum_x_square-sum_x**2)*(n*sum_y_square-sum_y**2))
if denominator==0:
return 0
r=numerator/denominator
return r
years_of_emp=[30,28,25,20]
annual_salary=[260000,360000,460000,560000]
correlation=pearson(years_of_emp,annual_salary)
print(f"one pearson:coefiicient between years of experience and annual salary is {correlation}")
OUTPUT:
one pearson:coefiicient between years of experience and annual salary is -0.9795260923726159
PROGRAM-2
AIM: Write a python script to find out rank correlation between the variables distance and price in
following data using spearmans rank correlation coefficient method
DESCRIPTION:
This program computes Spearman’s Rank Correlation Coefficient to measure the strength and
direction of the relationship between distance and price using rank-based correlation analysis.
Key Concepts Used:
1. Spearman’s Rank Correlation Formula – The formula applied is:

o r_h > 0 indicates a positive correlation (as distance increases, price increases).
o r_h < 0 indicates a negative correlation (as distance increases, price decreases).
o r_h = 0 indicates no correlation (distance and price are unrelated).
2. Ranking the Data (stats.rankdata(x)) – The program assigns ranks to each element in the
distance and price lists before computing correlation.
3. Difference Calculation (d = rank_x - rank_y) – Finds the difference between
corresponding ranks of x and y.
4. Square of Differences (d_squared = d**2) – Computes squared rank differences, essential
for the Spearman formula.
5. Summation & Final Calculation – The numerator and denominator are derived to compute
the correlation coefficient.
6. Use of scipy.stats (stats.rankdata()) – Automates rank assignment efficiently, handling
duplicate values by assigning average ranks.
7. Function Implementation (spearman(x, y)) – Encapsulates the logic to recalculate
correlation for different datasets easily.
8. Real-World Application – This method is used in economics, social sciences, and market
research to analyze relationships between variables like distance vs. price, study time vs.
grades, etc.
By executing this program, users can determine whether distance has an impact on price, helping in
decision-making and trend analysis.
SOURCE CODE:
import scipy.stats as stats
def spearman(x,y):
rank_x=stats.rankdata(x)
rank_y=stats.rankdata(y)
d=rank_x-rank_y
d_squared=d**2
n=len(x)
numerator=6*sum(d_squared)
denominator=n*(n**2-1)
rh=1-(numerator/denominator)
return rh
distance=[50,175,250,375,425,585,720,810,875,950]
price=[1.80,1.25,2.00,1.00,1.10,1.20,0.80,0.60,1.05,0.85]
rank_corr=spearman(distance,price)
print(f"The spearman rank correlation coefficient between distance and price is:{rank_corr}")
OUTPUT:
The spearman rank correlation coefficient between distance and price is: -0.7575757575757576
WEEK-7 Python Programs on NumPy Arrays, Linear algebra with NumPy
NumPy Arrays
PROGRAM-1
AIM: Write a python script to calculate the sum and multiplication of two arrays using dot() and
vdot() function.
DESCRIPTION:
NumPy Arrays:
 np.array is used to create arrays in NumPy.
 Here, arr1 and arr2 are 2x2 matrices (2D arrays).
Matrix Dot Product using np.dot():
 np.dot(arr1, arr2) performs standard matrix multiplication.
 It multiplies rows of arr1 with columns of arr2 and adds the results.
 Result is a new 2x2 matrix.
Vector Dot Product using np.vdot():
 np.vdot(arr1, arr2) flattens both arrays into 1D vectors and then does dot product.
 It multiplies each corresponding pair of elements and adds them all together.
 Result is a single number (scalar value).
SOURCE CODE:
import numpy as np
arr1=np.array([[4,5],[2,6]])
arr2=np.array([[7,1],[3,8]])
print(np.dot(arr1,arr2))
print(np.vdot(arr1,arr2))
OUTPUT:
[[43 44]
[32 50]]
87
PROGRAM-2
AIM: Write a python script to calculate inner products and outer products of two arrays using inner()
and outer() functions.
DESCRIPTION:
 NumPy Arrays:
o Arrays a and b are 1D arrays created using np.array.
o These arrays represent simple sequences of numbers.
 Inner Product using np.inner():
o The inner product multiplies elements at the same positions and adds them.
o It is like: 9*1 + 6*4 + 3*7, which gives a single number.
o The result is a scalar value.
 Outer Product using np.outer():
o The outer product multiplies each element of a with every element of b.
o This results in a 3x3 matrix where each value is a[i] * b[j].
o The result is a 2D matrix.
SOURCE CODE:
import numpy as np
a=np.array([9,6,3])
b=np.array([1,4,7])
i=np.inner(a,b)
print(i)
o=np.outer(a,b)
print(o)
OUTPUT:
54
[[ 9 36 63]
[ 6 24 42]
[ 3 12 21]]
PROGRAM-3
AIM: Write a python script to calculate multiplication of two arrays using matmul function.
DESCRIPTION:
 1D NumPy Arrays:
o Arrays a and b are created using np.array(), and both are one-dimensional.
o A 1D array is like a simple list of numbers.
o In this case:
 a = [3, 6, 9]
 b = [1, 4, 7]
o Both arrays have the same length, which is important for element-wise operations like
dot products.
 Matrix Multiplication using np.matmul():
o np.matmul() is used for matrix multiplication in NumPy.
o When both inputs are 1D arrays, it does the same thing as np.dot() — a dot product.
o The dot product works by multiplying each pair of elements at the same position in
the two arrays and then adding all the products:
3*1 + 6*4 + 9*7 = 3 + 24 + 63 = 90
o The result is a scalar value (a single number), not an array.
 Difference Between matmul, dot, and inner (for learning clarity):
o matmul(a, b) and dot(a, b) give the same result for 1D arrays.
o inner(a, b) also gives the same scalar result for 1D arrays.
o But if you use 2D or higher-dimensional arrays, these functions behave differently.
SOURCE CODE:
import numpy as np
a=np.array([3,6,9])
b=np.array([1,4,7])
i=np.matmul(a,b)
print(i)
OUTPUT:
90
PROGRAM-4
AIM: Write a python script to calculate linear matrix equation using linalg.solve() function.
DESCRIPTION:
 2D NumPy Arrays:
o Both a and b are 2D arrays (matrices) created using np.array().
o a is the coefficient matrix (left-hand side of equations).
o b is the right-hand side matrix (values after the equal sign).
 System of Linear Equations (AX = B):
o This equation represents a system of two equations with two unknowns.
o The function np.linalg.solve(a, b) tries to find the matrix X that satisfies this equation.
o It does this by applying mathematical operations similar to Gaussian elimination.
 Using np.linalg.solve():
o This function works only if matrix a is square (same number of rows and columns)
and invertible (has a unique solution).
o The output s is a 2x2 matrix that represents the solution for the variables.
 Why It's Useful:
o It's a very efficient way to solve equations in engineering, physics, and computer
science problems where systems of equations appear frequently.
SOURCE CODE:
import numpy as np
a=np.array([[7,8],[5,6]])
b=np.array([[1,2],[3,4]])
s=np.linalg.solve(a,b)
print(s)
OUTPUT:
[[ -9. -10.]
[ 8. 9.]]
PROGRAM-5
AIM: Write a python script calculate multiplicative inverse of a matrix using inv() function.
DESCRIPTION:
 2D NumPy Array as a Matrix:
o The variable a is a 2x2 matrix created using np.array().
o It represents a square matrix (same number of rows and columns), which is a
requirement for finding its inverse.
 Inverse of a Matrix:
o The inverse of a matrix A is a matrix A⁻¹ such that:
A * A⁻¹ = I, where I is the identity matrix.
o The identity matrix is like "1" for matrices — multiplying by it doesn’t change
anything.
o Not all matrices have an inverse — the matrix must be non-singular (i.e., its
determinant is not zero).
 Using np.linalg.inv():
o This function calculates the inverse of a given square matrix.
o If the matrix is not invertible (e.g., determinant is 0), it will raise an error.
o In this case, the inverse exists and the result is another 2x2 matrix.
 Why Matrix Inversion is Important:
o Inverse matrices are used to solve systems of equations (AX = B becomes X = A⁻¹B).
o They're also used in graphics, physics simulations, and machine learning models.
SOURCE CODE:
import numpy as np
a=np.array([[5,2],[4,1]])
inverse=np.linalg.inv(a)
print(inverse)
OUTPUT:
[[-0.33333333 0.66666667]
[ 1.33333333 -1.66666667]]
PROGRAM-6
AIM: Write a python script to calculate the trace of an array using trace() function.
DESCRIPTION:
 2D NumPy Array as a Matrix:
o a is a square matrix created using np.array().
o It contains values arranged in two rows and two columns.
 Main Diagonal of a Matrix:
o The main diagonal consists of elements from top-left to bottom-right.
o These are the elements where the row and column indices are the same.
 Trace using np.trace():
o np.trace(a) adds all the elements from the main diagonal.
o The result is a single number (scalar), which is the sum of those diagonal elements.
 Where Trace is Useful:
o Trace is important in many mathematical applications like matrix properties,
eigenvalues, and theoretical physics.
o It helps in summarizing certain characteristics of square matrices quickly.
SOURCE CODE:
import numpy as np
a=np.array([[5,2],[6,3]])
print(np.trace(a))
OUTPUT:
8
PROGRAM-7
AIM: Write a python script calculate the rank of a matrix using rank() function in numpy libraries.
DESCRIPTION:
 2D NumPy Array as a Matrix:
o a is a 2x2 matrix created using np.array().
o It represents a small square matrix with numerical values arranged in two rows and
two columns.
 Matrix Rank:
o The rank of a matrix is the number of linearly independent rows or columns.
o It tells us how many dimensions the data in the matrix actually spans.
o If all rows (or columns) are independent, the rank is full (equal to the number of rows
or columns).
 Using np.linalg.matrix_rank():
o This function calculates the rank automatically using numerical techniques.
o It checks whether the rows or columns are combinations of one another.
o The output is a single number showing how many independent rows or columns the
matrix has.
 Why Matrix Rank is Important:
o Rank is essential in solving linear systems, understanding matrix behavior, and
checking if equations have unique solutions.
o A full-rank matrix usually means a system of equations has a unique solution.
SOURCE CODE:
import numpy as np
a=np.array([[6,3],[7,2]])
print(np.linalg.matrix_rank(a))
OUTPUT:
2
PROGRAM-8
AIM: Write a python script to calculate eigen values and eigen vectors using eig() function.
DESCRIPTION:
 Square Matrix Creation:
o A is a 3x3 matrix created using np.array().
o It's a square matrix because it has the same number of rows and columns, which is
required for eigenvalue calculations.
 Eigenvalues and Eigenvectors:
o An eigenvalue tells how much the direction of an eigenvector is stretched or shrunk
when multiplied by the matrix.
o An eigenvector is a non-zero vector that only changes in scale (not direction) when
the matrix is applied to it.
 Using np.linalg.eig():
o This function returns two results:
 value: an array of eigenvalues of the matrix A.
 vector: a matrix where each column is an eigenvector corresponding to each
eigenvalue.
o It helps in understanding how a matrix transforms space.
 Why It’s Important:
o Eigenvalues and eigenvectors are used in areas like machine learning, quantum
mechanics, and structural analysis.
o They are also helpful in simplifying matrix operations and solving systems of
differential equations.
SOURCE CODE:
import numpy as np
A=np.array([[1,2,3],[3,2,-1],[4,0,-4]])
value,vector=np.linalg.eig(A)
print(value)
print(vector)
OUTPUT:
[-6.05798024 4.4666812 0.59129904]
[[ 0.44047381 -0.66326042 0.49735565]
[-0.27023519 -0.67962995 -0.75158903]
[-0.85612836 -0.31335084 0.43330277]]
PROGRAM-9
AIM: Write a python script to implement the numpy functions:
(i)linspace()
(ii)logspace()
(iii)asarray() functions
DESCRIPTION:
 np.linspace(start, stop, num):
o Creates a NumPy array with evenly spaced values between the given start and stop
values.
o The num parameter decides how many values to generate.
o Useful for creating linear ranges of values, especially in plotting and simulations.
 np.logspace(start, stop, num):
o Creates an array where the values are logarithmically spaced (base 10) between
10start10^{start}10start and 10stop10^{stop}10stop.
o The values increase very quickly because of the exponential growth.
o Useful for dealing with data that spans several orders of magnitude.
 np.asarray(data):
o Converts the input data (like a tuple, list, or sequence) into a NumPy array.
o Unlike np.array(), asarray() avoids copying data if it’s already an array.
o Useful when working with existing data structures in Python and converting them for
NumPy operations.
SOURCE CODE:
import numpy as np
linspace_result=np.linspace(0,10,num=4)
print("Linspace result:", linspace_result)
logspace_result=np.logspace(0,10,num=4)
print("Logspace result:", logspace_result)
asarray_result=np.asarray((2,5,8,6))
print("AsArray result:", asarray_result)
OUTPUT:
Linspace result: [ 0. 3.33333333 6.66666667 10. ]
Logspace result: [1.00000000e+00 2.15443469e+03 4.64158883e+06 1.00000000e+10]
AsArray result: [2 5 8 6]
PROGRAM-10
AIM: Write a python script to implement the numpy function arange()
DESCRIPTION:
 np.arange(stop) – Automatic Sequence Generation:
o This function generates a sequence of numbers starting from 0 and going up to stop -
1.
o In this example, np.arange(14) creates numbers from 0 to 13.
o The function returns a NumPy array, not a Python list.
 1D Array Output:
o The result is a one-dimensional array, meaning it has a single row of values.
o This is useful for performing linear operations, indexing, and simple data generation
tasks.
 Why Use np.arange() Instead of range()?:
o Unlike Python’s built-in range(), np.arange() gives you a NumPy array which
supports advanced mathematical operations.
o It works well with slicing, broadcasting, vectorized operations, and NumPy-specific
functions.
 Flexible Parameters (Beyond Just stop):
o You can also use it with custom start, stop, and step values like:
np.arange(2, 10, 2) → [2, 4, 6, 8]
o It allows easy control over how values are spaced in the array.
 Common Uses of np.arange():
o Creating sample data for testing.
o Setting up x-axis or time steps in plots.
o Initializing arrays for loops and iterations in numerical simulations.
SOURCE CODE:
import numpy as np
array=np.arange(14)
array
OUTPUT:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
Linear Algebra PROGRAM-1
AIM: Write a python script for input 2D array with dimensions N*M. Perform min function over
axis 1 and then find max of that.
DESCRIPTION:
 User Input for Matrix:Takes number of rows and columns, then collects matrix elements
row by row. Converts the list of lists into a NumPy array.
 Row-wise Minimum (axis=1):np.min(array, axis=1) finds the smallest value in each row.
 Maximum of Row Minima: np.max(rows_min) gives the highest value among all row-wise
minimums.
SOURCE CODE:
import numpy as np
N=int(input("Enter no. of rows(N):"))
M=int(input("Enter no. of columns(M):"))
array=[]
print("Enter elements row by row:")
for i in range(N):
row=list(map(int,input(f"Enter elements of {i+1}:").split()))
array.append(row)
array=np.array(array)
print(array)
rows_min=np.min(array,axis=1)
result=np.max(rows_min)
print("The maximum of row minimum is:",result)
OUTPUT:
Enter no. of rows(N): 3
Enter no. of columns(M): 3
Enter elements row by row:
Enter elements of 1: 3 2 1
Enter elements of 2: 6 5 4
Enter elements of 3: 9 8 7
[[3 2 1]
[6 5 4]
[9 8 7]] The maximum of row minimum is: 7
PROGRAM-2
AIM: Write a python script to create a null vector of size 10 but fifth value is 1.
DESCRIPTION:
 Creating a Zero-Filled Integer Array with np.zeros():
o np.zeros(10, dtype=int) creates a one-dimensional array containing 10 zeros.
o The dtype=int argument tells NumPy to store the values as integers, not as default
floating-point numbers.
o The array at this stage looks like:
[0 0 0 0 0 0 0 0 0 0]
 Indexing and Modifying Array Elements:
o In Python and NumPy, indexing starts at 0.
o So, vector[4] = 1 sets the 5th element to 1.
o vector[8] = 1 sets the 9th element to 1.
o The array after these modifications becomes:
[0 0 0 0 1 0 0 0 1 0]
 Why We Use This Approach:
o This type of array setup is used in binary marking or flagging specific positions.
o It is also commonly seen in one-hot encoding, where a specific position in a vector is
marked as 1 to indicate a class or category.
o It’s very useful in data preprocessing, machine learning, and custom binary
pattern creation.
SOURCE CODE:
import numpy as np
vector=np.zeros(10, dtype=int)
vector[4]=1
vector[8]=1
print(vector)
OUTPUT:
[0 0 0 0 1 0 0 0 1 0]
PROGRAM-3
AIM: Write a python script to reverse a vector(first element becomes last).
DESCRIPTION:
 User Input for Vector Size and Elements:
o n = int(input(...)) asks the user to enter the number of elements in the vector.
o vector = list(map(int, input(...).split())) reads the user’s input as a space-separated
string, splits it into parts, converts each part to an integer, and forms a list.
 Slicing for Reversal – [::-1]:
o vector[::-1] is a Python slicing technique that reads the list from end to start.
o It creates a new list with the same elements in reverse order.
o [::-1] means:
 Start from the end (:)
 Go till the beginning (:)
 Step by -1 (backwards)
 Storing and Printing the Reversed Vector:
o The reversed list is stored in reversed_vector.
o Finally, it prints the reversed version using:
print("Reversed vector:", reversed_vector)
 Why It’s Useful:
o Reversing a vector is a common task in many data manipulation and algorithmic
problems.
o It’s used in operations like palindrome checking, reversing a stack, or simply
flipping the order of data for processing.
SOURCE CODE:
import numpy as np
n=int(input("Enter size of vector:"))
vector=list(map(int,input("Enter element of vector:").split()))
reversed_vector=vector[::-1]
print("Reversed vector:",reversed_vector)
OUTPUT:
Enter size of vector: 5
Enter element of vector: 69 78 45 21 30
Reversed vector: [30, 21, 45, 78, 69]
PROGRAM-4
AIM: Write a python script to create a 3X3 identity matrix.
DESCRIPTION:
 np.eye(N) – Creating an Identity Matrix:
o np.eye(3) creates a 3x3 identity matrix.
o The main diagonal (from top-left to bottom-right) contains 1s.
o All other positions are filled with 0s.
o It creates a 2D NumPy array with these values.
 What is an Identity Matrix:
o A matrix in which all the diagonal elements are 1, and all non-diagonal elements
are 0.
o It is used as the multiplicative identity in matrix algebra.
o When any matrix is multiplied by an identity matrix (of the same size), the result is
the original matrix itself.
 Applications in Mathematics and Programming:
o Commonly used in matrix operations, transformations, linear algebra, and solving
systems of equations.
o Also used to initialize matrices in algorithms where no transformation is needed at
the start.
SOURCE CODE:
import numpy as np
identity_matrix=np.eye(3)
print(identity_matrix)
OUTPUT:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
PROGRAM-5
AIM: Write a python script to create a 10X10 array with random values and find minimum and
maximum values.
DESCRIPTION:
 np.random.randint(start, stop, size=(rows, columns)):
o This function generates a matrix filled with random integers in a given range.
o 10 is the inclusive lower limit, and 51 is the exclusive upper limit, meaning the values
will be between 10 and 50.
o size=(5, 5) tells NumPy to create a 5x5 matrix.
 Finding the Minimum Value – np.min(array):
o This function scans all the elements in the matrix and returns the smallest value
found.
o It works regardless of the matrix's shape and reduces the data to a single scalar value.
 Finding the Maximum Value – np.max(array):
o Similar to np.min(), this function returns the largest value found in the matrix.
o It is useful when analyzing data ranges or identifying peak values in datasets.
SOURCE CODE:
import numpy as np
array=np.random.randint(10,51,size=(5,5))
min_value=np.min(array)
max_value=np.max(array)
print("Array:\n",array)
print("Minimum value:",min_value)
print("Maximum value:",max_value)
OUTPUT:
Array:
[[31 47 10 27 39]
[26 34 18 43 41]
[46 50 44 15 26]
[33 24 43 48 50]
[20 38 47 15 10]]
Minimum value: 10
Maximum value: 50
PROGRAM-6
AIM: Write a python script to write a Numpy program to add, subtract, multiply, divide arguments
element-wise.
DESCRIPTION:
 Defining a Function with Multiple Return Values:
o The function array_np(arr1, arr2) performs four element-wise operations on the two
input arrays using NumPy functions.
o The results of addition, subtraction, multiplication, and division are returned together
as a tuple.
 Reading User Input for Array Elements:
o size = int(input(...)) asks the user for the number of elements in each array.
o List comprehensions like [float(x) for x in input(...).split()] convert space-separated
input into a list of floating-point numbers.
o np.array(...) converts these lists into NumPy arrays for easy numerical operations.
 Element-wise Array Operations Using NumPy Functions:
o np.add(arr1, arr2) adds corresponding elements from both arrays.
o np.subtract(arr1, arr2) subtracts elements of arr2 from arr1.
o np.multiply(arr1, arr2) multiplies corresponding elements.
o np.divide(arr1, arr2) divides each element of arr1 by the corresponding element of
arr2.
o These operations return new NumPy arrays of the same size.
 Why This Approach Is Useful:
o Element-wise operations are essential in data analysis, signal processing, and
mathematical computing.
o Using NumPy allows these operations to be done efficiently without writing loops.
o Functions like these help modularize the code and reuse logic wherever needed.
 Final Output Display:
o Each original array and the result of every operation is printed clearly to compare the
input and output side by side.
SOURCE CODE:
import numpy as np
def array_np(arr1,arr2):
addition=np.add(arr1,arr2)
sub=np.subtract(arr1,arr2)
mul=np.multiply(arr1,arr2)
div=np.divide(arr1,arr2)
return addition, sub, mul, div
size=int(input("Enter size of arrays: "))
arr1=np.array([float(x) for x in input(f"Enter {size} elements:").split()])
arr2=np.array([float(x) for x in input(f"Enter {size} elements:").split()])
addition, sub, mul, div=array_np(arr1,arr2)
print("Array1:",arr1)
print("Array2:",arr2)
print("Addition:",addition)
print("Subtraction:",sub)
print("Multiplication:",mul)
print("Division:",div)
OUTPUT:
Enter size of arrays: 3
Enter 3 elements: 12 10 20
Enter 3 elements: 12 15 16
Array1: [12. 10. 20.]
Array2: [12. 15. 16.]
Addition: [24. 25. 36.]
Subtraction: [ 0. -5. 4.]
Multiplication: [144. 150. 320.]
Division: [1. 0.66666667 1.25 ]
PROGRAM-7
AIM: Write a python script to write a numpy program to get floor, ceiling and truncated value of
elements of numpy array.
DESCRIPTION:
 Reading Multi-Row User Input to Create a 2D Array:
o The user is asked to enter the number of rows for the array.
o For each row, space-separated float numbers are taken and converted to a list using
map(float, input().split()).
o These lists are appended into a main list called array, forming a list of lists.
 Using NumPy Functions for Rounding Operations:
o Before using NumPy functions, the list of lists needs to be converted to a NumPy
array. This part is missing in the code and needs to be corrected:
array = np.array(array)
o np.floor(array) applies the floor function, which rounds each value down to the
nearest integer.
o np.ceil(array) applies the ceiling function, which rounds each value up to the nearest
integer.
o np.trunc(array) removes the decimal part from each number, effectively rounding
toward zero.
 Purpose of Each Function:
o Floor is used when you need the greatest integer less than or equal to a number.
o Ceil is used when you want the smallest integer greater than or equal to a number.
o Trunc simply chops off the decimal part without rounding.
 Why These Operations Matter:
o These functions are useful in scientific calculations, data preprocessing, rounding
rules, and computer graphics where precise integer control is required.
o They help in converting real-world floating data into formats usable for logic,
conditions, and iterations.
 Displaying the Result:
o The original array and the outputs of floor, ceiling, and truncation operations are
displayed clearly for comparison.
SOURCE CODE:
import numpy as np
array=[]
size=int(input("Enter size:"))
for i in range(size):
row=list(map(float,input(f"Enter elements of row {i+1}:").split()))
array.append(row)
print(array)
floor_val=np.floor(array)
ceil_val=np.ceil(array)
trunc_val=np.trunc(array)
print("Original array:",array)
print("Floor value:\n",floor_val)
print("Ceiling value:\n",ceil_val)
print("Truncated value:\n",trunc_val)
OUTPUT:
Enter size: 3
Enter elements of row 1: 12.3 15.4 18.9
Enter elements of row 2: 11.5 16.8 17.2
Enter elements of row 3: 23.6 15.9 18.7
[[12.3, 15.4, 18.9], [11.5, 16.8, 17.2], [23.6, 15.9, 18.7]]
Original array: [[12.3, 15.4, 18.9], [11.5, 16.8, 17.2], [23.6, 15.9, 18.7]]
Floor value:
[[12. 15. 18.]
[11. 16. 17.]
[23. 15. 18.]]
Ceiling value:
[[13. 16. 19.]
[12. 17. 18.]
[24. 16. 19.]]
Truncated value:
[[12. 15. 18.]
[11. 16. 17.]
[23. 15. 18.]]
PROGRAM-8
AIM: Write a python script to write a numpy program to multiply a 5x3 matrix by 3x2 matrix and
create a rear matrix product.
DESCRIPTION:
 Generating Random Matrices with np.random.randint():
o a = np.random.randint(1, 10, (5, 3)) creates a 5×3 matrix with random integers from 1
to 9.
o b = np.random.randint(1, 10, (3, 2)) creates a 3×2 matrix with random integers from
1 to 9.
o This function is commonly used for testing algorithms with randomized input data.
 Matrix Multiplication Using np.dot():
o np.dot(a, b) performs matrix multiplication of matrix a and matrix b.
o For multiplication to be valid:
 The number of columns in the first matrix (a with 3 columns)
 Must match the number of rows in the second matrix (b with 3 rows).
o The result is a 5×2 product matrix formed by combining rows of a and columns of b.
 Why Use Matrix Multiplication:
o It is used in many fields like machine learning, computer vision, physics, and
engineering.
o Matrix multiplication helps in performing linear transformations, data projections,
and solving systems of equations.
 Printing Matrices Neatly:
o print("Matrix A\n", a) displays the first matrix.
o print("Matrix B\n", b) displays the second matrix.
o print("Product Matrix:\n", prod) displays the result after multiplication.
SOURCE CODE:
import numpy as np
a=np.random.randint(1,10,(5,3))
b=np.random.randint(1,10,(3,2))
prod=np.dot(a,b)
print("Matrix A\n",a)
print("Matrix B\n",b)
print ("Product Matrix:\n",prod)
OUTPUT:
Matrix A
[[7 6 6]
[7 5 4]
[5 1 8]
[1 6 4]
[7 8 8]]
Matrix B
[[9 7]
[3 6]
[1 1]]
Product Matrix:
[[ 87 91]
[ 82 83]
[ 56 49]
[ 31 47]
[ 95 105]]
PROGRAM-9
AIM: Write a python script to write a numpy program to create an inner product of two arrays.
DESCRIPTION:
 User Input for Array Creation:
Takes sizes and elements for both arrays, then converts them into NumPy arrays.
 np.inner(arr1, arr2) – Inner Product:
Computes the sum of products of corresponding elements (dot product for 1D arrays).
 Display of Input and Result:
Prints both arrays and the inner product result.
SOURCE CODE:
import numpy as np
size1=int(input("Enter size1:"))
size2=int(input("Enter size2:"))
arr1=np.array([int(input(f"Enter element {i+1}"))for i in range(size1)])
arr2=np.array([int(input(f"Enter element {i+1}"))for i in range(size2)])
print(arr1,arr2)
inner_prod=np.inner(arr1,arr2)
print("The inner product:",inner_prod)
OUTPUT:
Enter size1: 3
Enter size2: 3
Enter element 1 12
Enter element 2 13
Enter element 3 14
Enter element 1 20
Enter element 2 21
Enter element 3 22
[12 13 14] [20 21 22]
The inner product: 821
PROGRAM-10
AIM: Write a python script to write a numpy program to complete the trigonometric sine, cosine,
and tangent array of angles given in degrees.
DESCRIPTION:
 User Input for 2D Array:
o The user specifies the number of rows (size) for the angle matrix.
o Each row is entered as space-separated integer values representing angles in degrees.
o These rows are collected into a list of lists to form a 2D array.
 Conversion to Radians – np.radians(array):
o NumPy trigonometric functions expect input in radians, not degrees.
o np.radians() automatically converts every degree value in the array to its radian
equivalent.
o This step is essential for accurate trigonometric calculations.
 Trigonometric Calculations:
o np.sin(angles_r) computes the sine of each radian value.
o np.cos(angles_r) computes the cosine of each radian value.
o np.tan(angles_r) computes the tangent of each radian value.
o These operations are applied element-wise to the entire matrix.
 Use of Trigonometric Functions:
o Useful in physics, engineering, and computer graphics.
o Can be applied to wave analysis, motion studies, or coordinate transformations.
 Display of Results:
o The original angle matrix (in degrees) is printed for clarity.
o Sine, cosine, and tangent values are shown in separate matrices, matching the input
structure.
o This allows easy comparison between the angle and its corresponding trig values.
SOURCE CODE:
import numpy as np
array=[]
size=int(input("Enter size:"))
for i in range(size):
row=list(map(int,input(f"Enter element {i+1}:").split()))
array.append(row)
print(array)
angles_r=np.radians(array)
sine_val=np.sin(angles_r)
cos_val=np.cos(angles_r)
tan_val=np.tan(angles_r)
print("Angles (degrees):",array)
print("Sine values:",sine_val)
print("Cosine values:",cos_val)
print("Tangent values:",tan_val)
OUTPUT:
Enter size: 1
Enter element 1: 25
[[25]]
Angles (degrees): [[25]]
Sine values: [[0.42261826]]
Cosine values: [[0.90630779]]
Tangent values: [[0.46630766]]
Linear Algebra
PROGRAM-1
AIM: Write a python script to write a numpy program to calculate the absolute value element wise.
DESCRIPTION:
 User Input for Array Creation:
o The user specifies the number of elements in the array.
o A list comprehension collects each integer input and converts it to a NumPy array.
 np.abs(arr) – Absolute Value Calculation:
o Computes the absolute value (non-negative version) of each element in the array.
o Negative numbers become positive, and positive numbers remain unchanged.
o Useful in mathematical operations where only the magnitude matters.
 Display of Results:
o Prints the original array for reference.
o Prints the array of absolute values, showing the result of the transformation.
SOURCE CODE:
import numpy as np
size=int(input("Enter the number of elements in the array:"))
arr=np.array([int(input(f"Enter element {i+1}:")) for i in range(size)])
abs_values=np.abs(arr)
print("Original array:",arr)
print("Absolute values:",abs_values)
OUTPUT:
Enter the number of elements in the array: 5
Enter element 1: -5
Enter element 2: -3
Enter element 3: 0
Enter element 4: 3
Enter element 5: 6
Original array: [-5 -3 0 3 6]
Absolute values: [5 3 0 3 6]

PROGRAM-2
AIM: Write a python script to flatten two arrays.
DESCRIPTION:
 2D Array Creation with np.array():
o arrA and arrB are defined as 2×2 matrices using nested lists.
o Each matrix contains integer elements arranged in rows and columns.
 Flattening and Appending with np.append():
o np.append(arrA, arrB) flattens both matrices and joins them into a single 1D array.
o The result contains all elements of arrA followed by all elements of arrB, in row-
major order.
o This does not preserve the original matrix shape.
 Use of Flattened Arrays:
o Flattened arrays are useful in data preprocessing, vector operations, and when
feeding data into models or functions that require 1D input.
 Display of Final Result:
o The final array is printed as a flat sequence of values from both input arrays.
SOURCE CODE:
import numpy as np
arrA=np.array([[11,21],[30,46]])
arrB=np.array([[19,21],[46,21]])
arr_flat=np.append(arrA,arrB)
print(arr_flat)
OUTPUT:
[11 21 30 46 19 21 46 21]
PROGRAM-3
AIM: Write a python script to remove a sub array from a numpy array.
DESCRIPTION:
 Creating Arrays with np.arange() and List Assignment:
o np.arange(6) initially creates an array with values from 0 to 5.
o Then, arr1 is reassigned manually with the list [1, 3, 5, 9].
 Deleting an Element with np.delete(array, index):
o np.delete(arr1, 2) removes the element at index 2 (which is the number 5) from the
array.
o This function returns a new array; it does not modify the original in place.
 Use of Deletion:
o Useful for removing unwanted or specific data in preprocessing.
o Index-based removal is quick and efficient for NumPy arrays.
 Display of Arrays:
o Prints the original array and the updated array after deletion.
o Also prints the value that was intended to be removed (object = 3, although not
directly used for deletion here).
SOURCE CODE:
import numpy as np
arr1=np.arange(6)
print("The array is:",arr1)
object=3
arr1=[1,3,5,9]
print("The array is:",arr1)
arr=np.delete(arr1,2)
print("After deleting",object,"new array is")
print(arr)
OUTPUT:
The array is: [0 1 2 3 4 5]
The array is: [1, 3, 5, 9]
After deleting 3 new array is
[1 3 9]
PROGRAM-4
AIM: Write a python script to write a numpy program to illustrate horizontal and vertical stacking.
DESCRIPTION:
 User Input for Arrays:
Converts space-separated inputs into NumPy arrays using map() and np.array().
 Horizontal Stack – np.hstack((x, y)):
Combines arrays side by side into a single 1D array.
 Vertical Stack – np.vstack((x, y)):
Combines arrays one below the other into a 2D array with two rows.
 Display of Results:
Prints both original arrays and their stacked forms.
SOURCE CODE:
import numpy as np
x=np.array(list(map(int,input(f"Enter elements of the first array:").split())))
y=np.array(list(map(int,input(f"Enter elements of the second array:").split())))
print("\nFirst array:\n",x)
print("\nSecond array:\n",y)
print("Horizontally stacked array:\n",np.hstack((x,y)))
print("Vertically stacked array:\n",np.vstack((x,y)))
OUTPUT:
Enter elements of the first array: 1 2 3 4 5
Enter elements of the second array: 16 17 18 19 20

First array:
[1 2 3 4 5]

Second array:
[16 17 18 19 20]
Horizontally stacked array:
[ 1 2 3 4 5 16 17 18 19 20]
Vertically stacked array:
[[ 1 2 3 4 5]
[16 17 18 19 20]]
PROGRAM-5
AIM: Write a python script to write a numpy program to sort the elements of the array.
DESCRIPTION:
 Creating a NumPy Array from User Input:
o The program asks the user to enter space-separated integers.
o These values are first converted into a list of integers using map(int, input().split()).
o Then, the list is passed to np.array() to form a 1D NumPy array called a.
o This makes it easy to apply NumPy’s vectorized operations on the array.
 Sorting the Array – np.sort(a):
o np.sort() is used to sort the elements of the array in ascending order.
o This function returns a new sorted array; it does not modify the original array in
place.
o Sorting helps in organizing data and is widely used in searching, ranking, and
statistical analysis.
 Immutability of Original Array:
o The original array a remains unchanged, which allows the program to compare both
the original and sorted arrays.
o This is useful for understanding how sorting affects the dataset without altering the
original structure.
 Display of Results:
o First, the original array is printed for clarity.
o Next, the sorted version is printed to show the rearranged values in ascending order.
o This helps in observing the transformation clearly.
SOURCE CODE:
import numpy as np
a=np.array(list(map(int,input("Enter the elements of the array:").split())))
print("Original array is:",a)
print("Sorted array is:",np.sort(a))
OUTPUT:
Enter the elements of the array: 4 2 70 56 24
Original array is: [ 4 2 70 56 24]
Sorted array is: [ 2 4 24 56 70]

PROGRAM-6
AIM: Write a python script to write a Numpy program to add, subtract, multiply, divide arguments
element-wise.
DESCRIPTION:
1. Input Handling:
The program starts by asking the user for the size of the arrays. It then takes two sets of inputs, each
containing that many numbers. These inputs are collected using space-separated input from the user
and are converted to floating-point numbers using list comprehension. These values are then stored
in NumPy arrays using np.array() for further processing.
Using floating-point numbers ensures that mathematical operations, especially division, are handled
accurately even when the values are not whole numbers.
2. Use of NumPy Arrays:
NumPy arrays allow mathematical operations to be applied efficiently across all elements without
writing loops. This is done using vectorized operations, which are optimized for performance. Once
the input lists are converted to NumPy arrays, various mathematical operations can be performed
directly between arrays.
3. Function Definition: array_np(arr1, arr2)
This function handles the computation of four basic operations between the two input arrays:
 np.add() performs element-wise addition.
 np.subtract() performs element-wise subtraction.
 np.multiply() performs element-wise multiplication.
 np.divide() performs element-wise division.
Each of these functions works on corresponding elements of the arrays. The computed results are
then returned from the function so they can be printed in the main part of the program.
4. Function Call and Output:
In the main part of the code, the array_np() function is called with the two NumPy arrays as
arguments. The returned values from this function (addition, subtraction, multiplication, division) are
stored in separate variables. These results, along with the original arrays, are displayed using print
statements.
This clear separation of logic into input, function, and output makes the program more organized and
easier to understand.
SOURCE CODE:
import numpy as np
def array_np(arr1,arr2):
addition=np.add(arr1,arr2)
sub=np.subtract(arr1,arr2)
mul=np.multiply(arr1,arr2)
div=np.divide(arr1,arr2)
return addition, sub, mul, div
size=int(input("Enter size of arrays: "))
arr1=np.array([float(x) for x in input(f"Enter {size} elements:").split()])
arr2=np.array([float(x) for x in input(f"Enter {size} elements:").split()])
addition, sub, mul, div=array_np(arr1,arr2)
print("Array1:",arr1)
print("Array2:",arr2)
print("Addition:",addition)
print("Subtraction:",sub)
print("Multiplication:",mul)
print("Division:",div)
OUTPUT:
Enter size of arrays: 3
Enter 3 elements: 12 10 20
Enter 3 elements: 12 15 16
Array1: [12. 10. 20.]
Array2: [12. 15. 16.]
Addition: [24. 25. 36.]
Subtraction: [ 0. -5. 4.]
Multiplication: [144. 150. 320.]
Division: [1. 0.66666667 1.25 ]

PROGRAM-7
AIM: Write a python script to write a numpy program to get floor, ceiling and truncated value of
elements of numpy array.
DESCRIPTION:
np.array() Conversion:
You first take input in the form of a list of lists from the user. Since NumPy functions like floor(),
ceil(), and trunc() require NumPy arrays, the input list must be converted using np.array(array). This
allows the array to be processed with vectorized mathematical operations.
2. np.floor():
This function rounds down each value in the array to the nearest integer less than or equal to the
value. It works element-wise, so all elements in the array are processed individually.
3. np.ceil():
This function rounds up each element in the array to the nearest integer greater than or equal to the
value. Like floor(), it applies to each value independently and returns a new array.
4. np.trunc():
This function removes the decimal part of each number in the array without rounding. It truncates the
number toward zero, keeping the integer part only. It also works element-wise across all elements of
the array.
5. Output Section:
After the input is taken and processed using the above NumPy functions, the original array and all
the resulting arrays (floor, ceil, and trunc values) are printed in a clean and easy-to-read format. The
final output helps visualize how each function affects the values in the array.
SOURCE CODE:
import numpy as np
array=[]
size=int(input("Enter size:"))
for i in range(size):
row=list(map(float,input(f"Enter elements of row {i+1}:").split()))
array.append(row)
print(array)
floor_val=np.floor(array)
ceil_val=np.ceil(array)
trunc_val=np.trunc(array)
print("Original array:",array)
print("Floor value:",floor_val)
print("Ceiling value:",ceil_val)
print("Truncated value:",trunc_val)
OUTPUT:
Enter size: 3
Enter elements of row 1: 12.3 15.4 18.9
Enter elements of row 2: 11.5 16.8 17.2
Enter elements of row 3: 23.6 15.9 18.7
[[12.3, 15.4, 18.9], [11.5, 16.8, 17.2], [23.6, 15.9, 18.7]]
Original array: [[12.3, 15.4, 18.9], [11.5, 16.8, 17.2], [23.6, 15.9, 18.7]]
Floor value: [[12. 15. 18.]
[11. 16. 17.]
[23. 15. 18.]]
Ceiling value: [[13. 16. 19.]
[12. 17. 18.]
[24. 16. 19.]]
Truncated value: [[12. 15. 18.]
[11. 16. 17.]
[23. 15. 18.]]

PROGRAM-8
AIM: Write a python script to write a numpy program to multiply a 5x3 matrix by 3x2 matrix and
create a rear matrix product.
DESCRIPTION:
Matrix Creation using np.random.randint():
Two matrices a and b are created using the NumPy function np.random.randint(), which generates
random integers. The first matrix a has dimensions 2×3, and the second matrix b has dimensions
3×2. These shapes are chosen so that they can be multiplied using standard matrix multiplication
rules, where the number of columns in the first matrix matches the number of rows in the second
matrix.
Matrix Multiplication using np.dot():
The product of the matrices a and b is computed using the np.dot() function. This function performs
matrix multiplication by taking the dot product of rows from the first matrix and columns from the
second. The resulting matrix, prod, has a shape of 2×2, since it combines the row count of the first
matrix and the column count of the second.
Display of Output Matrices:
The original matrices a and b, as well as their product prod, are printed for reference. Displaying all
three matrices helps to understand the structure of the input data and verify the correctness of the
multiplication. The output shows how the values from the two matrices contribute to each element in
the resulting matrix.
SOURCE CODE:
import numpy as np
a=np.random.randint(1,10,(2,3))
b=np.random.randint(1,10,(3,2))
prod=np.dot(a,b)
print("Matrix A\n",a)
print("Matrix B\n",b)
print ("Product Matrix:\n",prod)
OUTPUT:
Matrix A [[3 7 8]
[8 6 8]]
Matrix B [[6 4]
[9 3]
[2 1]]
Product Matrix: [[ 97 41]
[118 58]]

PROGRAM-9
AIM: Write a python script to write a numpy program to create an inner product of two arrays
DESCRIPTION:
Array Input Using Loops:
The program starts by taking two sizes from the user, one for each array. Using list comprehension
with a for loop, it collects individual elements based on the specified sizes. The inputs are stored as
NumPy arrays using np.array(), allowing for efficient mathematical operations. This method ensures
that both arrays are flexible in length and support dynamic input.
Calculation Using np.inner():
The np.inner() function is used to compute the inner product of the two arrays. For one-dimensional
arrays, the inner product is the same as the dot product — it multiplies corresponding elements from
both arrays and then sums them up. This operation is efficient and concise with NumPy, and it avoids
the need for manual iteration or calculation.
Display of Results:
After computing the inner product, the program prints both arrays and the resulting value. Showing
the original arrays helps in verifying the input, and displaying the result of the inner product gives
clarity on how the two input vectors interacted during the calculation.
SOURCE CODE:
import numpy as np
size1=int(input("Enter size1:"))
size2=int(input("Enter size2:"))
arr1=np.array([int(input(f"Enter element {i+1}"))for i in range(size1)])
arr2=np.array([int(input(f"Enter element {i+1}"))for i in range(size2)])
print(arr1,arr2)
inner_prod=np.inner(arr1,arr2)
print("The inner product:",inner_prod)
OUTPUT:
Enter size1: 2
Enter size2: 2
Enter element 1 12
Enter element 2 14
Enter element 1 23
Enter element 2 4
[12 14] [23 4]
The inner product: 332

PROGRAM-10
AIM: Write a python script to write a numpy program to complete the trigonometric sine, cosine,
and tangent array of angles given in degrees.
DESCRIPTION:
Input and Array Formation: The user enters angle values row by row, which are stored in a list of
lists and converted into a NumPy array for easier processing.
Conversion Using np.radians(): Since trigonometric functions in NumPy require angles in radians,
the degree values are converted using np.radians().
Trigonometric Calculations: Functions like np.sin(), np.cos(), and np.tan() are applied element-
wise to the array to compute the respective values.
Output Section: The original angle array (in degrees) and the calculated sine, cosine, and tangent
values are printed for easy comparison.
SOURCE CODE:
import numpy as np
array=[]
size=int(input("Enter size:"))
for i in range(size):
row=list(map(int,input(f"Enter element {i+1}:").split()))
array.append(row)
print(array)
angles_r=np.radians(array)
sine_val=np.sin(angles_r)
cos_val=np.cos(angles_r)
tan_val=np.tan(angles_r)
print("Angles (degrees):",array)
print("Sine values:",sine_val)
print("Cosine values:",cos_val)
print("Tangent values:",tan_val)
OUTPUT:Enter size: 1 Enter element 1: 25
[[25]]
Angles (degrees): [[25]]
Sine values: [[0.42261826]]
Cosine values: [[0.90630779]]
Tangent values: [[0.46630766]]
PROGRAM-11
AIM: Write a python script to write a numpy program to calculate the absolute value element wise.
DESCRIPTION:
Input and Array Creation:
The program begins by asking the user to enter the number of elements they want to include in the
array. Then, using a list comprehension within a NumPy array function, it collects each element from
the user one by one. This results in a one-dimensional NumPy array containing the user-provided
integers. This method is efficient and ensures that the data is stored in a format that can easily be
processed by NumPy’s functions.
Calculation Using np.abs():
Once the array is formed, the program uses the np.abs() function to calculate the absolute value of
each element in the array. The absolute value of a number is its distance from zero on the number
line, regardless of direction. This means negative numbers are converted to positive, while positive
numbers and zero remain unchanged. NumPy handles this operation element-wise, so the
transformation is done efficiently without the need for explicit loops.
Output Section:
After performing the absolute value computation, the program prints both the original array and the
resulting array with absolute values. This dual output helps the user to easily compare and
understand how each element has been changed or remained the same after applying the np.abs()
function. It also demonstrates the usefulness of NumPy for vectorized mathematical operations.
SOURCE CODE:
import numpy as np
size=int(input("Enter the number of elements in the array:"))
arr=np.array([int(input(f"Enter element {i+1}:")) for i in range(size)])
abs_values=np.abs(arr)
print("Original array:",arr)
print("Absolute values:",abs_values)
OUTPUT:
Enter the number of elements in the array: 3
Enter element 1: 2
Enter element 2: -7
Enter element 3: -6
Original array: [ 2 -7 -6]
Absolute values: [2 7 6]

PROGRAM-12
AIM: Write a python script to flatten two arrays.
DESCRIPTION:
Array Initialization:
Two 2D NumPy arrays, arrA and arrB, are defined with the same shape of 2×2. Each array contains
integers arranged in a matrix format. These arrays represent the initial data that will be manipulated
using NumPy's array-handling functions.
Flattening and Appending Using np.append():
The program uses the np.append() function to combine arrA and arrB into a single array. By default,
np.append() flattens both input arrays into 1D form and then appends the second array (arrB) to the
end of the first (arrA). This function does not concatenate along specific dimensions unless specified
with the axis parameter. Since no axis is mentioned, it treats the data as one-dimensional.
Output Section:
After the arrays are appended, the resulting 1D array is printed. This output shows all the elements
from both arrA and arrB placed sequentially in a single flat array. It helps the user see how multi-
dimensional arrays can be combined and flattened for further processing or storage.
SOURCE CODE:
import numpy as np
arrA=np.array([[11,21],[30,46]])
arrB=np.array([[19,21],[46,21]])
arr_flat=np.append(arrA,arrB)
print(arr_flat)
OUTPUT:
[11 21 30 46 19 21 46 21]
PROGRAM-13
AIM: Write a python script to remove a sub array from a numpy array.
DESCRIPTION:
Initial Array with np.arange():
The program first creates an array arr1 using np.arange(6), which generates a NumPy array with
values from 0 to 5. However, this array is immediately overwritten in the next step, so it does not
affect the rest of the program.
Redefining the Array:
The array arr1 is then redefined as a standard Python list with elements [1, 3, 5, 9]. This list
represents the actual data on which the delete operation will be performed. Redefining it like this
overrides the earlier NumPy array.
Deletion Using np.delete():
The program uses np.delete() to remove the element at index 2 from arr1. Indexing in Python starts
from 0, so the element at index 2 is 5. The deletion does not modify the original list in-place; instead,
it returns a new NumPy array with the specified index removed. The variable object is set to 3, but it
is not used in the deletion — it only appears in the output message.
Output Section:
The program prints the array before and after deletion to show the effect of np.delete(). The resulting
array excludes the third element (5), demonstrating how individual elements can be removed from a
NumPy-compatible list using index-based deletion.
SOURCE CODE:
import numpy as np
arr1=np.arange(6)
print("The array is:",arr1)
object=3
arr1=[1,3,5,9]
print("The array is:",arr1)
arr=np.delete(arr1,2)
print("After deleting",object,"new array is")
print(arr)
OUTPUT:
The array is: [0 1 2 3 4 5]
The array is: [1, 3, 5, 9]
After deleting 3 new array is
[1 3 9]

PROGRAM-14
AIM: Write a python script to write a numpy program to illustrate horizontal and vertical stacking.
DESCRIPTION:
Input and Array Creation:
The user is prompted to enter elements for two arrays. Each input line is split into separate values,
converted to integers using map(), and stored in NumPy arrays x and y. These arrays are one-
dimensional, meaning each consists of a single row of elements.
Horizontal Stacking Using np.hstack():
The function np.hstack((x, y)) horizontally stacks the two arrays. This means it joins the second array
y to the end of the first array x, creating a single longer one-dimensional array. The elements of both
arrays appear side by side in the result, making it useful when you want to concatenate arrays along
columns.
Vertical Stacking Using np.vstack():
The np.vstack((x, y)) function stacks the two arrays vertically. This creates a two-dimensional array
with x as the first row and y as the second. Even though x and y are 1D arrays, np.vstack() converts
them into a 2D format with each array forming its own row.
Output Section:
The program displays both input arrays and then shows the results of horizontal and vertical
stacking. This allows the user to visually understand the difference between stacking side-by-side
versus stacking one on top of the other, which is important when manipulating array shapes for
matrix operations or data formatting.
SOURCE CODE:
import numpy as np
x=np.array(list(map(int,input(f"Enter elements of the first array:").split())))
y=np.array(list(map(int,input(f"Enter elements of the second array:").split())))
print("\nFirst array:\n",x)
print("\nSecond array:\n",y)
print("Horizontally stacked array:\n",np.hstack((x,y)))
print("Vertically stacked array:\n",np.vstack((x,y)))
OUTPUT:Enter elements of the first array: 1 2 3 4 5
Enter elements of the second array: 16 17 18 19 20
First array: [1 2 3 4 5]
Second array: [16 17 18 19 20]
Horizontally stacked array:
[ 1 2 3 4 5 16 17 18 19 20]
Vertically stacked array: [[ 1 2 3 4 5]
[16 17 18 19 20]]
PROGRAM-15
AIM: Write a python script to write a numpy program to sort the elements of the array.
DESCRIPTION:
Input and Array Creation:
The program prompts the user to enter elements for the array. The input string is split into individual
values and converted to integers using map(). These values are then stored in a NumPy array a,
allowing for efficient numerical operations and manipulation.
Displaying the Original Array:
Before performing any operations, the program prints the original array. This step helps the user
compare the unsorted and sorted versions of the array and better understand how the sorting function
works.
Sorting Using np.sort():
The np.sort() function is used to sort the array in ascending order. It returns a new sorted array
without modifying the original one. This function works efficiently on NumPy arrays and is useful
for ordering data, especially when preparing it for further analysis or display.
Output Section:
Finally, the program prints the sorted version of the array. Displaying both the original and sorted
arrays side by side gives a clear view of how the elements have been rearranged, making the effect of
the sort operation easy to understand.
SOURCE CODE:
import numpy as np
a=np.array(list(map(int,input("Enter the elements of the array:").split())))
print("Original array is:",a)
print("Sorted array is:",np.sort(a))
OUTPUT:
Enter the elements of the array: 4 2 70 56 24
Original array is: [ 4 2 70 56 24]
Sorted array is: [ 2 4 24 56 70]
WEEK-8 Python Programs for creation and manipulation of
Data Frames using Pandas Library
PROGRAM-1
AIM: Write a python script to create a series using python list [10, 20, 30, 40, 50]. Display the series
and set the custom index ['a', 'b', 'c', 'd', 'e']. Access elements using both default and numerical and
custom indices
DESCRIPTION:
Default Series Creation:
A Series named obj is created with values [10, 20, 30, 40, 50] using default integer indexing (0 to 4).
Its index is printed using obj.index.
Custom Indexed Series:
Another Series, obj2, is created with the same values but with custom string indices ['a', 'b', 'c', 'd',
'e'], making the data labels more meaningful.
Output Display:
Both the default and custom-indexed Series are displayed, showing how pandas allows flexible and
descriptive indexing.
SOURCE CODE:
import pandas as pd
obj = pd.Series([10, 20, 30, 40, 50])
print(obj)
print(obj.index)
obj2 = pd.Series([10, 20, 30, 40, 50], index=['a', 'b', 'c', 'd', 'e'])
obj2
OUTPUT:
0 10
1 20 2 30
3 40 4 50
dtype: int64
RangeIndex(start=0, stop=5, step=1)
a 10 b 20
c 30 d 40
e 50
dtype: int64

PROGRAM-2
AIM: Write a python script to perform arithmetic operations.
DESCRIPTION:
Series Creation:
Two pandas Series, a and b, are created with integer values. a contains [1, 2, 3, 4, 5] and b contains
[5, 4, 3, 2, 1]. These two Series will be used for arithmetic operations.
Arithmetic Operations Using NumPy:
The program uses NumPy functions to perform element-wise arithmetic operations between a and b:
 Addition: np.add(a, b) adds the corresponding elements of a and b together.
 Subtraction: np.subtract(a, b) subtracts elements of b from a element-wise.
 Multiplication: np.multiply(a, b) multiplies corresponding elements of a and b.
 Division: np.divide(a, b) divides each element of a by the corresponding element of b.
Output Section:
The results of all four operations are printed: the sum, difference, product, and quotient. Each
operation is performed element-wise, meaning the operation is done for each corresponding pair of
elements from the two Series.
SOURCE CODE:
import pandas as pd
import numpy as np
a = pd.Series([1, 2, 3, 4, 5])
b = pd.Series([5, 4, 3, 2, 1])
print(np.add(a, b))
print(np.subtract(a, b))
print(np.multiply(a, b))
print(np.divide(a, b))
OUTPUT:
0 6 1 6 2 6 3 6 4 6
dtype: int64
0 -4 1 -2 2 0 3 2 4 4
dtype: int64
0 5 1 8 2 9 3 8 4 5
dtype: int64
0 0.2 1 0.5 2 1.0 3 2.0 4 5.0
dtype: float64
PROGRAM-3
AIM: Write a python script to create a series and identify missing valueswith isnull() and replace
them with 0 using fillna().
DESCRIPTION:
DataFrame Creation:
A pandas DataFrame named df is created from a dictionary data, where each key represents a
column, and the values are lists. The column names are 'a', 'b', 'c', and 'd', with the values [1], [2],
[None], and [4] respectively. Notice that the column 'c' contains a None value, which represents a
missing or NaN value in pandas.
Handling Missing Values with fillna():
The fillna(0) method is applied to the DataFrame. This method fills any missing values (NaN or
None) in the DataFrame with the specified value, which in this case is 0. This operation does not
modify the original DataFrame but returns a new DataFrame with the missing value in column 'c'
replaced by 0.
Output Section:
The program applies the fillna() method, but since the result is not printed, the missing value in
column 'c' is replaced by 0. To view the result, you could either print the DataFrame or assign the
returned value to a new variable.
SOURCE CODE:
import pandas as pd
import numpy as np
data = {'a': [1], 'b': [2], 'c': [None], 'd': [4]}
df = pd.DataFrame(data)
df.fillna(0)
OUTPUT:
PROGRAM-4
AIM: Write a python script to identify missing values and replace them with column mean.
DESCRIPTION:
DataFrame Creation:
A DataFrame is created from a dictionary, where each key represents a column and each value is a
list of data for that column. The pandas.DataFrame() function converts this dictionary into a
structured table, which allows you to efficiently store and manipulate data.
Adding a New Row with Missing Values:
A new row is added to the DataFrame using the df.loc[len(df)] method, where df.loc accesses
specific locations by index. The new row contains a NaN value to represent missing data. In pandas,
NaN (Not a Number) is used to denote missing or undefined values.
Filling Missing Values with the Mean:
After adding the row with the missing salary, the program calculates the mean of the existing data in
the 'Salary' column. This mean value is then used to fill in the missing value using the fillna()
method. The inplace=True argument modifies the original DataFrame directly, replacing missing
values with the computed mean.
Why Use fillna() with Mean:
Filling missing values with the mean is a standard method used to handle missing data. It helps
maintain the integrity of the dataset while avoiding the introduction of extreme values that could
skew the results. The mean is often used for numerical columns when the data is reasonably uniform
and not significantly impacted by outliers.
Key Points:
 NaN is used to represent missing or undefined values in pandas.
 The mean() method calculates the average of numeric values in a column.
 The fillna() method replaces missing values with a specified value, such as the mean.
 The inplace=True argument modifies the DataFrame without needing to create a new one.
SOURCE CODE:
import pandas as pd
import numpy as np
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 70000]}
df = pd.DataFrame(data)
print(df)
df.loc[len(df)] = ['Eve', 28, np.nan]
print("Data Frame with missing salary value:")
print(df)
salary_mean = df['Salary'].mean()
df['Salary'].fillna(salary_mean, inplace=True)
print("In Data Frame after filling missing salary with mean:")
print(df)
OUTPUT:
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 35 70000
Data Frame with missing salary value:
Name Age Salary
0 Alice 25 50000.0
1 Bob 30 60000.0
2 Charlie 35 70000.0
3 Eve 28 NaN
In Data Frame after filling missing salary with mean:
Name Age Salary
0 Alice 25 50000.0
1 Bob 30 60000.0
2 Charlie 35 70000.0
3 Eve 28 60000.0
PROGRAM-5
AIM: Write a python script to write a dataframe to a csv file and read it back into a new frame.
DESCRIPTION:
DataFrame Creation: A DataFrame is created using a dictionary with columns 'Name', 'Age', and
'Salary'.
Writing to CSV:The to_csv() method saves the DataFrame to a CSV file named 'employee.csv',
without including row indices.
Reading from CSV: The read_csv() method reads the 'employee.csv' file into a new DataFrame,
demonstrating how to load data back from a CSV.
Purpose of CSV: CSV is a widely used format for storing and exchanging tabular data due to its
simplicity and ease of use.
SOURCE CODE:
import pandas as pd
import numpy as np
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Salary': [50000, 60000, 70000]}
df = pd.DataFrame(data)
print(df)
df.to_csv('employee.csv', index=False)
new_df = pd.read_csv('employee.csv')
print('Contents of employees.csv:')
print(new_df)
OUTPUT:
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 35 70000
Contents of employees.csv:
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 35 70000
PROGRAM-6
AIM: Write a python script to create a dataframe with height and weight. Compute the correlation
and covariance
DESCRIPTION:
DataFrame Creation:
A DataFrame is created with two columns: 'Height' and 'Weight', containing numerical data for five
individuals.
Correlation Calculation:
The corr() method calculates the Pearson correlation coefficient between height and weight. This
value ranges from -1 (perfect negative correlation) to 1 (perfect positive correlation). A value close to
1 indicates a strong positive relationship between the two variables.
Covariance Calculation:
The cov() method calculates the covariance between height and weight. Covariance measures how
the two variables vary together, but unlike correlation, it is not standardized and depends on the units
of the variables. Positive covariance indicates both variables increase together, while negative
covariance indicates one increases as the other decreases.
Key Concepts:
 Correlation: Measures the strength and direction of a linear relationship.
 Covariance: Indicates the degree to which two variables change together, but is not unit-free.
SOURCE CODE:
import pandas as pd
data = {'Height': [150, 160, 170, 180, 190],
'Weight': [50, 60, 65, 75, 85]}
df = pd.DataFrame(data)
corr = df['Height'].corr(df['Weight'])
cov = df['Height'].cov(df['Weight'])
print("Correlation:", corr)
print("Covariance:", cov)
OUTPUT:
Correlation: 0.9948497511671098
Covariance: 212.5
PROGRAM-7
AIM: Write a python script to create a dataframe with certain columns and save it to excel file
DESCRIPTION:
pip install openpyxl
Requirement already satisfied: openpyxl in c:\users\user\appdata\local\programs\python\python313\
lib\site-packages (3.1.5)Note: you may need to restart the kernel to use updated packages.
Requirement already satisfied: et-xmlfile in c:\users\user\appdata\local\programs\python\python313\
lib\site-packages (from openpyxl) (2.0.0)
DataFrame Creation:
A DataFrame is created from a dictionary data containing product information. The dictionary has
keys "Product", "Price", and "Stock", with corresponding lists of data for three products: Pen,
Notebook, and Eraser. Each column in the DataFrame represents a product's name, price, and
available stock.
Saving Data to an Excel File:
The to_excel() method is used to save the DataFrame to an Excel file named 'inventory.xlsx'. The
index=False argument ensures that the row index is not included in the saved file, making the Excel
sheet cleaner. This method allows you to easily export the DataFrame to a widely used file format for
further processing or sharing.
Message Confirmation:
After saving the DataFrame to the Excel file, a message is printed confirming that the operation was
successful and the data has been saved to 'inventory.xlsx'.
Why Use Excel Files:
Excel files are commonly used for storing and sharing tabular data. By saving data in Excel format,
you ensure compatibility with spreadsheet software and allow users to manipulate and analyze the
data easily.
SOURCE CODE:
import pandas as pd
data = {
"Product": ["Pen", "Notebook", "Eraser"],
"Price": [10, 50, 5],
"Stock": [100, 200, 300]
}
df = pd.DataFrame(data)
df.to_excel("inventory.xlsx", index=False)
print("DataFrame has been saved to 'inventory.xlsx'")
OUTPUT: DataFrame has been saved to 'inventory.xlsx'
PROGRAM-8
AIM: Write a python script to create a dataframe from merging data from two different excel
files/sheets.
DESCRIPTION:
Reading Excel Sheets:
The read_excel() function reads data from two sheets in the 'sales.xlsx' file, loading the data for
"January" and "February" into january_df and february_df respectively.
Merging DataFrames:
The pd.concat() function combines the two DataFrames into a single merged_df, with
ignore_index=True ensuring a continuous index.
Purpose of Merging:
Merging allows you to combine data from multiple sources or time periods for easier analysis or
aggregation.
SOURCE CODE:
import pandas as pd
january_df = pd.read_excel("sales.xlsx", sheet_name="January")
february_df = pd.read_excel("sales.xlsx", sheet_name="February")
merged_df = pd.concat([january_df, february_df], ignore_index=True)
print("Merged DataFrame:")
print(merged_df)
OUTPUT:
Merged DataFrame:
product price date
0 pen 5.0 NaT
1 pencil 10.0 NaT
2 eraser 8.0 NaT
3 scale 15.0 NaT
4 sketch 20.0 NaT
5 NaN NaN 2025-01-25
6 NaN NaN 2025-01-26
7 NaN NaN 2025-01-27
8 NaN NaN 2025-01-28
9 NaN NaN 2025-01-29
PROGRAM-9
AIM: Write a python script to display the names of sheets and first three rows data from the excel.
DESCRIPTION:
Reading All Sheets from an Excel File:
In this program, the read_excel() function from pandas is used with the argument sheet_name=None,
which instructs pandas to read all sheets from the 'workbook.xlsx' file. This loads the data from each
sheet into a dictionary called sheets_dict. Each key in this dictionary represents a sheet name, and
each corresponding value is a DataFrame containing the data from that sheet. By using
sheet_name=None, you can work with multiple sheets within a single file in a convenient way.
Printing Sheet Names:
The keys() method is used to print out the names of all the sheets available in the Excel file. This
allows you to see the structure of the file and the various sheets it contains.
Iterating Through Each Sheet:
A for loop is used to iterate through each item in the sheets_dict dictionary. The loop accesses each
sheet's name (sheet_name) and its corresponding data (df). For each sheet, the program prints the
first three rows using the head(3) method, which displays a snapshot of the data, helping you quickly
inspect the content of each sheet.
Why Use This Approach:
This approach is useful when you need to work with an Excel file containing multiple sheets. It
allows you to dynamically load and inspect the data from all sheets without needing to specify the
sheet names individually. This is especially helpful when the sheet names are unknown or when
dealing with files with many sheets.
SOURCE CODE:
import pandas as pd
sheets_dict = pd.read_excel("workbook.xlsx", sheet_name=None)
print("Sheet names:", sheets_dict.keys())
for sheet_name, df in sheets_dict.items():
print(f"\nFirst three rows of sheet '{sheet_name}':")
print(df.head(3))
OUTPUT:
Sheet names: dict_keys(['Sheet1'])
First three rows of sheet 'Sheet1':
name age
0 ram 40
1 sita 34
2 laxman 38
PROGRAM-11
AIM: Write a python script that sorts the data in an Excel file based on grades and saves it.
DESCRIPTION:
Reading the Excel File:
The read_excel() function from pandas is used to read the data from the 'student.xlsx' file. This file
likely contains information about students, including their grades, and the data is loaded into the df
DataFrame.
Sorting the Data:
The sort_values() method is used to sort the DataFrame based on the 'grade' column in descending
order. The argument ascending=False ensures that the sorting is done from highest to lowest grade.
This is useful for ranking or prioritizing students based on their grades.
Saving the Sorted Data:
The sorted DataFrame (df_sorted) is saved to a new Excel file called 'student_sorted.xlsx' using the
to_excel() method. The argument index=False ensures that the row index is not included in the
output file, making it cleaner and more focused on the actual data.
Message Confirmation:
Finally, the program prints a message confirming that the data has been sorted by grade in
descending order, letting the user know that the operation was successful.
Why Sorting is Important:
Sorting data based on a specific column, like grades, is commonly used in tasks such as ranking
students, filtering high-performing individuals, or organizing records in a meaningful way.
SOURCE CODE:
import pandas as pd
df=pd.read_excel("student.xlsx")
df_sorted=df.sort_values(by="grade",ascending=False)
df_sorted.to_excel("student_sorted.xlsx",index=False)
print("Data has been sorted by grade in descending order")
OUTPUT:
Data has been sorted by grade in descending order
PROGRAM-
AIM: Write a python script
DESCRIPTION:

SOURCE CODE:

OUTPUT:
PROGRAM-
AIM: Write a python script
DESCRIPTION:

SOURCE CODE:

OUTPUT:
PROGRAM-
AIM: Write a python script
DESCRIPTION:

SOURCE CODE:

OUTPUT:
PROGRAM-
AIM: Write a python script
DESCRIPTION:

SOURCE CODE:

OUTPUT:
PROGRAM-
AIM: Write a python script
DESCRIPTION:

SOURCE CODE:

OUTPUT:
PROGRAM-
AIM: Write a python script
DESCRIPTION:

SOURCE CODE:

OUTPUT:

You might also like