Python sem
#1 Write a Python program to perform Linear Algebra functions on Arrays using Numpy.
import numpy as np
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
Addition of two arrays
sum_AB = np.add(A, B)
print("Sum of A and B:")
print(sum_AB)
Subtraction of two arrays
diff_AB = np.subtract(A, B)
print("\nDifference of A and B:")
print(diff_AB)
Scalar multiplication
scalar = 2
scalar_mul_A = scalar * A
print("\nScalar multiplication of A by", scalar)
print(scalar_mul_A)
Dot product of two arrays
dot_product = np.dot(A, B)
print("\nDot product of A and B:")
print(dot_product)
Transpose of an array
transpose_A = np.transpose(A)
print("\nTranspose of A:")
print(transpose_A)
det_A = np.linalg.det(A)
print("\nDeterminant of A:", det_A)
Inverse of an array
inv_A = np.linalg.inv(A)
print("\nInverse of A:")
print(inv_A)
#2 Store the Faculty details in a excel file and display the details of the faculty using Pandas.
import pandas as pd
Faculty details
faculty_data = {
'Name': ['John Doe', 'Jane Smith', 'David Johnson'],
'Department': ['Computer Science', 'Electrical Engineering', 'Mechanical Engineering'],
'Position': ['Assistant Professor', 'Associate Professor', 'Professor'],
'Experience': [5, 8, 12]
}
Create a DataFrame
df = pd.DataFrame(faculty_data)
Save DataFrame to Excel file
file_name = 'faculty_details.xlsx' df.to_excel(file_name, index=False)
Read the Excel file
df_from_excel = pd.read_excel(file_name)
Display the details
print(df_from_excel)
#3 Write a Python program to perform various operation on List. # Define a sample list
my_list = [1, 2, 3, 4, 5]
Print the original list
print("Original list:", my_list)
Append an element to the list
my_list.append(6)
print("After appending 6:", my_list)
Remove an element from the list
my_list.remove(3)
print("After removing 3:", my_list)
Insert an element at a specific index
my_list.insert(2, 7)
print("After inserting 7 at index 2:", my_list)
Extend the list with another list
my_list.extend([8, 9, 10])
print("After extending with [8, 9, 10]:", my_list)
Sort the list
my_list.sort()
print("After sorting:", my_list)
Reverse the list
my_list.reverse()
print("After reversing:", my_list)
Find the index of an element
index = my_list.index(5)
print("Index of 5:", index)
Count occurrences of an element
count = my_list.count(7)
print("Count of 7:", count)
Clear the list
my_list.clear()
print("After clearing the list:", my_list)
#4 Write a Python program to perform string functions. # Define a sample string
my_string = "Hello, World!" # Print the original string
print("Original string:", my_string)
Convert the string to uppercase
upper_case = my_string.upper()
print("Uppercase:", upper_case)
Convert the string to lowercase
lower_case = my_string.lower()
print("Lowercase:", lower_case)
Capitalize the string (first character uppercase, rest lowercase)
capitalized = my_string.capitalize()
print("Capitalized:", capitalized)
Get the length of the string
length = len(my_string)
print("Length:", length)
Count occurrences of a substring
count = my_string.count("o")
print("Count of 'o':", count)
Check if the string starts with a particular substring
starts_with = my_string.startswith("Hello")
print("Starts with 'Hello':", starts_with)
Check if the string ends with a particular substring
ends_with = my_string.endswith("World!")
print("Ends with 'World!':", ends_with)
Find the index of a substring
index = my_string.find("World")
print("Index of 'World':", index)
Replace a substring with another substring
replaced = my_string.replace("World", "Python")
print("After replacement:", replaced)
Split the string into a list of substrings
split = my_string.split(", ")
print("After splitting:", split)
Join a list of strings into one string using a delimiter
joined = ", ".join(["Goodbye", "Earth"])
print("After joining:", joined)
#5 Write a Python program to perform various operations on Tuples. # Define a sample tuple
my_tuple = (1, 2, 3, 4, 5)
Print the original tuple
print("Original tuple:", my_tuple)
Access elements of the tuple
print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])
Slicing tuple
print("Sliced tuple:", my_tuple[1:4])
Concatenate tuples
other_tuple = (6, 7, 8)
concatenated_tuple = my_tuple + other_tuple
print("Concatenated tuple:", concatenated_tuple)
Find length of tuple
length = len(my_tuple)
print("Length of tuple:", length)
Check if an element exists in tuple
print("Is 3 present in tuple?", 3 in my_tuple)
Count occurrences of an element in tuple
count = my_tuple.count(2)
print("Count of 2 in tuple:", count)
Find index of an element in tuple
index = my_tuple.index(4)
print("Index of 4 in tuple:", index)
Convert tuple to list
list_from_tuple = list(my_tuple)
print("Tuple converted to list:", list_from_tuple)
Convert list back to tuple
tuple_from_list = tuple(list_from_tuple)
print("List converted back to tuple:", tuple_from_list)
#6 Write a Python program to display student marks as pie, bar charts using Pandas and
Matplotlib.
import pandas as pd
import matplotlib.pyplot as plt
Sample student marks data
student_data = {
'Name': ['John', 'Emily', 'Tom', 'Alice', 'Bob'],
'Maths': [85, 90, 75, 80, 95],
'Science': [88, 92, 78, 85, 90],
'English': [82, 88, 72, 78, 85]
}
Create a DataFrame
df = pd.DataFrame(student_data)
Calculate total marks for each student
df['Total'] = df['Maths'] + df['Science'] + df['English']
Plot pie chart for total marks
plt.figure(figsize=(8, 6))
plt.pie(df['Total'], labels=df['Name'], autopct='%1.1f%%', startangle=140)
plt.title('Student Total Marks')
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show()
Plot bar chart for each subject
plt.figure(figsize=(10, 6))
df.plot(x='Name', y=['Maths', 'Science', 'English'], kind='bar')
plt.title('Student Marks in Each Subject')
plt.xlabel('Student')
plt.ylabel('Marks')
plt.xticks(rotation=45)
plt.legend(title='Subject')
plt.show()
#7 Write a Python program to perform various set operations. # Define sample sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
Print the original sets
print("Set 1:", set1)
print("Set 2:", set2)
Union of sets
union_set = set1.union(set2)
print("Union of sets:", union_set)
Intersection of sets
intersection_set = set1.intersection(set2)
print("Intersection of sets:", intersection_set)
Difference between sets
difference_set = set1.difference(set2)
print("Difference between set1 and set2:", difference_set)
Symmetric difference between sets
symmetric_difference_set = set1.symmetric_difference(set2)
print("Symmetric difference between sets:", symmetric_difference_set)
Check if one set is subset of another
is_subset = set1.issubset(set2)
print("Is set1 a subset of set2?", is_subset)
Check if one set is superset of another
is_superset = set1.issuperset(set2)
print("Is set1 a superset of set2?", is_superset)
Add an element to a set
set1.add(6)
print("After adding 6 to set1:", set1)
Remove an element from a set
set2.remove(8)
print("After removing 8 from set2:", set2)
Clear a set
set1.clear()
print("After clearing set1:", set1)
#8 Store the Employee details in a excel file and display the details of the faculty using Pandas.
import pandas as pd
Employee details
employee_data = {
'Name': ['John Doe', 'Jane Smith', 'David Johnson'],
'Department': ['HR', 'Marketing', 'Finance'],
'Position': ['Manager', 'Assistant Manager', 'Financial Analyst'],
'Salary': [60000, 50000, 55000]
}
Create a DataFrame
df = pd.DataFrame(employee_data)
Save DataFrame to Excel file
file_name = 'employee_details.xlsx' df.to_excel(file_name, index=False)
Read the Excel file
df_from_excel = pd.read_excel(file_name)
Display the details
print(df_from_excel)
#9 Write a Python program to various functions in Dictionary. # Define a samp
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
Print the original dictionary
print("Original dictionary:", my_dict)
Accessing elements of the dictionary
print("Name:", my_dict['name'])
print("Age:", my_dict.get('age'))
Adding a new key-value pair to the dictionary
my_dict['job'] = 'Engineer' print("After adding job:", my_dict)
Removing a key-value pair from the dictionary
removed_value = my_dict.pop('age')
print("Removed age:", removed_value)
print("After removing age:", my_dict)
Checking if a key exists in the dictionary
print("Is 'name' present in dictionary?", 'name' in my_dict)
print("Is 'city' present in dictionary?", my_dict.contains('city'))
Getting list of keys and values
keys = my_dict.keys()
values = my_dict.values()
print("Keys:", keys)
print("Values:", values)
Getting list of key-value pairs (items)
items = my_dict.items()
print("Items:", items)
Copying dictionary
copied_dict = my_dict.copy()
print("Copied dictionary:", copied_dict)
Clearing the dictionary
my_dict.clear()
print("After clearing dictionary:", my_dict)
#10 Write a Python program to display student marks as pie, bar charts using Pandas and
Matplotlib
import pandas as pd
import matplotlib.pyplot as plt
Sample student marks data
student_data = {
'Name': ['John', 'Emily', 'Tom', 'Alice', 'Bob'],
'Maths': [85, 90, 75, 80, 95],
'Science': [88, 92, 78, 85, 90],
'English': [82, 88, 72, 78, 85]
}
Create a DataFrame
df = pd.DataFrame(student_data)
Calculate total marks for each student
df['Total'] = df['Maths'] + df['Science'] + df['English']
Plot pie chart for total marks
plt.figure(figsize=(8, 6))
plt.pie(df['Total'], labels=df['Name'], autopct='%1.1f%%', startangle=140)
plt.title('Student Total Marks')
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show()
Plot bar chart for each student
plt.figure(figsize=(10, 6))
df.plot(x='Name', y=['Maths', 'Science', 'English'], kind='bar')
plt.title('Student Marks in Each Subject')
plt.xlabel('Student')
plt.ylabel('Marks')
plt.xticks(rotation=45)
plt.legend(title='Subject')
plt.show()
#11 Write a Python program to calculate the area and perimeter of a Circle.
import math
def calculate_circle_area(radius): """ Calculate the area of a circle given its radius. """ return math.pi * radius**2
def calculate_circle_perimeter(radius): """ Calculate the perimeter (circumference) of a circle given its radius. """ return 2 * math.pi * radius
Input radius from the user
radius = float(input("Enter the radius of the circle: "))
Calculate area and perimeter
area = calculate_circle_area(radius)
perimeter = calculate_circle_perimeter(radius)
Print the results
print("Area of the circle:", round(area, 2))
print("Perimeter of the circle:", round(perimeter, 2))
#12 Design simple Calculator using functions in Python.
Addition function
def add(x, y):
return x + y
Subtraction function
def subtract(x, y):
return x - y
Multiplication function
def multiply(x, y):
return x * y
Division function
def divide(x, y):
if y == 0:
return "Error! Division by zero is not allowed." else:
return x / y
Main function to perform calculations
def calculator():
print("Select operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = input("Enter choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print("Result:", add(num1, num2))
elif choice == '2':
print("Result:", subtract(num1, num2))
elif choice == '3':
print("Result:", multiply(num1, num2))
elif choice == '4':
print("Result:", divide(num1, num2))
else:
print("Invalid input")
calculator(