Python
Python
#This will be a common line for all programs where numpy is needed
import numpy as np
1. Create a 3x3 matrix filled with random numbers and find its transpose.
# Create a 3x3 matrix filled with random numbers and find its transpose
matrix = np.random.rand(3, 3)
transpose = matrix.T
print("Original Matrix:\n", matrix)
print("Transpose:\n", transpose)
2. Generate an array of 100 evenly spaced values between 0 and 10, and
compute their square roots.
# Generate an array of 100 evenly spaced values between 0 and 10, and compute their
square roots
array = np.linspace(0, 10, 100)
sqrt_array = np.sqrt(array)
print("Array:\n", array)
print("Square Roots:\n", sqrt_array)
3. Perform element-wise multiplication of two arrays.
#Perform element-wise multiplication of two arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
element_wise_multiplication = array1 * array2
print("Element-wise Multiplication:\n", element_wise_multiplication)
4. Create a 2D array and calculate the mean, median, and standard deviation
of its elements.
#Create a 2D array and calculate the mean, median, and standard deviation of its
elements
data = np.random.rand(5, 5)
mean = np.mean(data)
median = np.median(data)
std_dev = np.std(data)
print("Mean:", mean)
print("Median:", median)
print("Standard Deviation:", std_dev)
5. Find the dot product and cross product of two vectors.
#Find the dot product and cross product of two vectors
vector1 = np.array([1, 2, 3])
vector2 = np.array([4, 5, 6])
dot_product = np.dot(vector1, vector2)
cross_product = np.cross(vector1, vector2)
print("Dot Product:", dot_product)
print("Cross Product:\n", cross_product)
14. Create a structured array with named columns (e.g., age, height).
#Create a structured array with named columns (e.g., age, height)
structured_array = np.array([(25, 5.8), (30, 6.0), (35, 5.5)],
dtype=[('age', 'i4'), ('height', 'f4')])
print("Structured Array:\n", structured_array)
print("Ages:", structured_array['age'])
print("Heights:", structured_array['height'])
Pandas Problems:
#This will be a common line for all programs where pandas is needed
import pandas as pd
1. Load a CSV file and display summary statistics for its numerical columns.
#Load a CSV file and display summary statistics for its numerical columns
# Assuming 'data.csv' is the file to be loaded
df = pd.read_csv('data.csv')
print("Summary Statistics:\n", df.describe())
2. Filter rows in a DataFrame based on a condition (e.g., values greater than a
threshold).
# 7. Filter rows in a DataFrame based on a condition (e.g., values greater than a
threshold)
# Assuming the DataFrame has a column named 'value'
filtered_df = df[df['value'] > 50]
print("Filtered Rows:\n", filtered_df)
3. Group the DataFrame by a categorical column and calculate aggregate
statistics like sum or mean.
#Group the DataFrame by a categorical column and calculate aggregate statistics like
sum or mean
# Assuming the DataFrame has a column named 'category'
grouped_df = df.groupby('category').sum()
print("Grouped Data:\n", grouped_df)
4. Handle missing values in a DataFrame by replacing them with the column
mean.
# 9. Handle missing values in a DataFrame by replacing them with the column mean
# Assuming the DataFrame has missing values
df_filled = df.fillna(df.mean())
print("DataFrame with Missing Values Handled:\n", df_filled)
5. Merge two DataFrames on a common column and display the result.
#Merge two DataFrames on a common column and display the result
# Assuming two DataFrames 'df1' and 'df2' with a common column 'id'
df1 = pd.DataFrame({'id': [1, 2, 3], 'value1': [10, 20, 30]})
df2 = pd.DataFrame({'id': [2, 3, 4], 'value2': [40, 50, 60]})
merged_df = pd.merge(df1, df2, on='id', how='inner')
print("Merged DataFrame:\n", merged_df)
Generate a random password of a specific length. It uses the random module
along with string to include letters, digits, and symbols:
import random
import string
def generate_password(length):
if length < 4: # Ensure password has enough characters for complexity
print("Password length should be at least 4.")
return None
# Define character pools
letters = string.ascii_letters
digits = string.digits
symbols = string.punctuation
# Ensure the password contains at least one letter, digit, and symbol
all_characters = letters + digits + symbols
password = [
random.choice(letters),
random.choice(digits),
random.choice(symbols)
]
# Example usage
password_length = int(input("Enter the desired password length: "))
password = generate_password(password_length)
if password:
print("Generated Password:", password)
Write a Python program to create and manage a simple student database using a
dictionary. Each student ID serves as a key, and its value is a dictionary
containing details like name, marks, and other information:
1. Add a Student: Allows you to add a student with an ID, name, and marks.
2. View Student Details: Displays the details of a student by ID.
3. Update Student Details: Lets you modify the name and marks of a student.
4. Delete a Student: Removes a student from the database using their ID.
5. Display All Students: Lists all the students in the database.
6. Exit: Terminates the program.
This program provides basic CRUD (Create, Read, Update, Delete) functionality for
managing student data.
def display_menu():
print("\n--- Student Database ---")
print("1. Add a Student")
print("2. View Student Details")
print("3. Update Student Details")
print("4. Delete a Student")
print("5. Display All Students")
print("6. Exit")
def add_student(database):
student_id = input("Enter Student ID: ")
if student_id in database:
print("Student ID already exists!")
return
name = input("Enter Name: ")
marks = float(input("Enter Marks: "))
details = {"Name": name, "Marks": marks}
database[student_id] = details
print("Student added successfully!")
def view_student(database):
student_id = input("Enter Student ID: ")
if student_id in database:
print("Student Details:", database[student_id])
else:
print("Student ID not found!")
def update_student(database):
student_id = input("Enter Student ID: ")
if student_id in database:
name = input("Enter Updated Name: ")
marks = float(input("Enter Updated Marks: "))
database[student_id] = {"Name": name, "Marks": marks}
print("Student details updated successfully!")
else:
print("Student ID not found!")
def delete_student(database):
student_id = input("Enter Student ID: ")
if student_id in database:
del database[student_id]
print("Student deleted successfully!")
else:
print("Student ID not found!")
def display_all_students(database):
if database:
for student_id, details in database.items():
print(f"ID: {student_id}, Name: {details['Name']}, Marks: {details['Marks']}")
else:
print("No students found!")
# Main Program
student_database = {}
while True:
display_menu()
choice = int(input("Enter your choice: "))
if choice == 1:
add_student(student_database)
elif choice == 2:
view_student(student_database)
elif choice == 3:
update_student(student_database)
elif choice == 4:
delete_student(student_database)
elif choice == 5:
display_all_students(student_database)
elif choice == 6:
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
Write a Python program to count the number of occurrences of each word in a
string.
1. Case-insensitivity: The program converts the input string to lowercase to treat
words like "Hello" and "hello" as the same.
2. Punctuation Removal: It removes punctuation using string.maketrans() to
ensure words like "word," and "word" are treated as the same.
3. Word Splitting: The split() method splits the string into a list of words based on
whitespace.
4. Counting Words: A dictionary (word_count) is used to track the number of
occurrences of each word. The get() method is used to handle new words
efficiently.
def count_word_occurrences(input_string):
# Convert the string to lowercase to make the count case-insensitive
input_string = input_string.lower()
return word_count
# Example usage
input_string = input("Enter a string: ")
result = count_word_occurrences(input_string)
print("Word Occurrences:")
for word, count in result.items():
print(f"{word}: {count}")
Write a Python program to calculate the sum of digits in a number.
1. Absolute Value: The program ensures the number is positive by using abs(), so
it works for both positive and negative numbers.
2. String Conversion: The number is converted to a string to iterate over each
digit.
3. Summation: The program uses a generator expression to calculate the sum of
the digits.
4. Interactive Input: The user enters a number, and the program calculates and
displays the result.
def sum_of_digits(number):
# Make sure the number is positive
number = abs(number)
# Convert the number to a string, iterate over each digit, and compute the sum
digit_sum = sum(int(digit) for digit in str(number))
return digit_sum
# Example usage
number = int(input("Enter a number: "))
result = sum_of_digits(number)
print("Sum of digits:", result)
Write a Python program to find the intersection of two lists:
1. Set Conversion: Both lists are converted into sets, which allow efficient
operations like intersections.
2. Intersection Operation: The & operator finds the common elements between
two sets.
3. List Conversion: The result is converted back to a list for easy readability.
def find_intersection(list1, list2):
# Use set intersection to find common elements
intersection = list(set(list1) & set(list2))
return intersection
# Example usage
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
def calculate_circle(radius):
# Calculate area and perimeter
area = math.pi * radius ** 2
perimeter = 2 * math.pi * radius
# Example usage
radius = float(input("Enter the radius of the circle: "))
area, perimeter = calculate_circle(radius)
return True
# Example usage
num = int(input("Enter a number: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Write a Python program to generate the first n prime numbers based on user
input:
1. List for Primes: A list primes is used to store the prime numbers as they are
found.
2. Prime Checking: For each number starting from 2, the program checks
divisibility by all numbers up to its square root.
3. While Loop: The loop continues until the length of the primes list equals n.
4. Efficient Increment: The program checks each number in sequence and skips
to the next if it’s not prime.
def generate_primes(n):
primes = [] # List to store prime numbers
num = 2 # Start with the smallest prime number
if is_prime:
primes.append(num) # Add the prime number to the list
return primes
# Example usage
n = int(input("Enter the number of prime numbers to generate: "))
if n > 0:
prime_numbers = generate_primes(n)
print(f"The first {n} prime numbers are: {prime_numbers}")
else:
print("Please enter a positive integer.")
Write a Python program to find the second largest element in a list:
1. Remove Duplicates: The program uses set() to remove duplicate elements from
the list.
2. Sort in Descending Order: The unique elements are sorted in descending order
using sort(reverse=True).
3. Check for Valid Input: If there are fewer than 2 unique elements, the function
returns None.
4. Second Largest: The second largest element is found at index 1 of the sorted
list.
def find_second_largest(numbers):
# Remove duplicates and sort the list in descending order
unique_numbers = list(set(numbers))
unique_numbers.sort(reverse=True)
# Example usage
numbers = [10, 20, 20, 40, 30]
second_largest = find_second_largest(numbers)
if second_largest is None:
print("The list doesn't have a second largest element.")
else:
print("The second largest element is:", second_largest)
Write a Python program to validate an email address format using a regular
expression (regex):
1. Regex Pattern:
o ^[a-zA-Z0-9._%+-]+: Matches the username part (letters, digits, dots,
underscores, etc.).
o @[a-zA-Z0-9.-]+: Matches the domain name part after "@".
o \.[a-zA-Z]{2,}$: Matches the top-level domain (e.g., .com, .org), which must
be at least 2 characters long.
2. Validation:
o The re.match() function checks if the input email matches the defined
pattern.
o It returns True if the pattern matches and False otherwise.
3. Interactive Input:
o The user enters an email address, and the program validates its format.
import re
def validate_email(email):
# Define a regex pattern for validating email addresses
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
# Example usage
email = input("Enter an email address: ")
if validate_email(email):
print(f"{email} is a valid email address.")
else:
print(f"{email} is not a valid email address.")