0% found this document useful (0 votes)
0 views22 pages

Python

Uploaded by

sreyagoswami38
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views22 pages

Python

Uploaded by

sreyagoswami38
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

NumPy Problems:

#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)

6. Create a 4x4 identity matrix.


# Create a 4x4 identity matrix
identity_matrix = np.eye(4)
print("Identity Matrix:\n", identity_matrix)
7. Generate a 1D array of 20 random integers between 1 and 100, and extract
only the even numbers.
#Generate a 1D array of 20 random integers between 1 and 100, and extract only the
even numbers
array = np.random.randint(1, 101, 20)
even_numbers = array[array % 2 == 0]
print("Original Array:\n", array)
print("Even Numbers:\n", even_numbers)
8. Create a 3D array and flatten it into a 1D array.
#Create a 3D array and flatten it into a 1D array
array_3d = np.random.rand(3, 3, 3)
array_flattened = array_3d.flatten()
print("3D Array:\n", array_3d)
print("Flattened Array:\n", array_flattened)
9. Replace all values greater than a threshold in a 2D array with zero.
#Replace all values greater than a threshold in a 2D array with zero
threshold = 0.5
array_2d = np.random.rand(4, 4)
array_2d[array_2d > threshold] = 0
print("Modified Array:\n", array_2d)
10. Create two random arrays and calculate their Manhattan distance.
# Create two random arrays and calculate their Manhattan distance
array1 = np.random.rand(3)
array2 = np.random.rand(3)
manhattan_distance = np.sum(np.abs(array1 - array2))
print("Manhattan Distance:", manhattan_distance)
11. Normalize an array to have values between 0 and 1.
#Normalize an array to have values between 0 and 1
array = np.random.randint(10, 100, 10)
normalized_array = (array - np.min(array)) / (np.max(array) - np.min(array))
print("Original Array:", array)
print("Normalized Array:", normalized_array)

12. Generate a 2D array and rotate it 90 degrees clockwise.


#Generate a 2D array and rotate it 90 degrees clockwise
array_2d = np.random.rand(3, 3)
rotated_array = np.rot90(array_2d, -1)
print("Original Array:\n", array_2d)
print("Rotated Array:\n", rotated_array)

13. Find the indices of all non-zero elements in an array.


#Find the indices of all non-zero elements in an array
array = np.array([0, 3, 0, 4, 5])
non_zero_indices = np.nonzero(array)
print("Non-zero Indices:", non_zero_indices)

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:

1. Character Pools: The program uses string.ascii_letters, string.digits, and


string.punctuation to include a mix of characters.
2. Complexity Guarantee: It ensures the password includes at least one letter, one
digit, and one symbol.
3. Password Length: The user can specify the desired length, and the program fills
the remaining characters with random choices from all pools.
4. Randomness: The random.shuffle() ensures the characters are in a random
order.

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)
]

# Fill the remaining password length with random characters


password += random.choices(all_characters, k=length - 3)

# Shuffle the password list to randomize the order of characters


random.shuffle(password)

# Join the characters into a single string


return ''.join(password)

# 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.

# Student Database Program

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()

# Remove punctuation from the string


import string
input_string = input_string.translate(str.maketrans('', '', string.punctuation))

# Split the string into words


words = input_string.split()

# Count occurrences of each word


word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1

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]

result = find_intersection(list1, list2)


print("Intersection of lists:", result)
Example Output:
If list1 = [1, 2, 3, 4, 5] and list2 = [4, 5, 6, 7, 8], the output will be:
Intersection of lists: [4, 5]
Write a Python program to calculate the area and perimeter (circumference) of a
circle based on its radius:
import math

def calculate_circle(radius):
# Calculate area and perimeter
area = math.pi * radius ** 2
perimeter = 2 * math.pi * radius

return area, perimeter

# Example usage
radius = float(input("Enter the radius of the circle: "))
area, perimeter = calculate_circle(radius)

print(f"Area of the circle: {area:.2f}")


print(f"Perimeter (Circumference) of the circle: {perimeter:.2f}")
Write a Python program to check if a number is prime.
1. Prime Number Definition: A number is prime if it is greater than 1 and has no
divisors other than 1 and itself.
2. Optimization: The program checks for divisors only up to the square root of the
number, which significantly improves efficiency for large numbers.
3. Edge Cases: Numbers less than 2 are handled as non-prime.
def is_prime(number):
# Handle edge cases for numbers less than 2
if number < 2:
return False

# Check for factors up to the square root of the number


for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False

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

while len(primes) < n:


# Check if the current number is prime
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break

if is_prime:
primes.append(num) # Add the prime number to the list

num += 1 # Increment the number to check the next one

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)

# Check if the list has at least two unique elements


if len(unique_numbers) < 2:
return None # No second largest element
return unique_numbers[1] # Second largest element

# 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,}$'

# Use re.match() to check if the email matches the pattern


if re.match(email_pattern, email):
return True
else:
return False

# 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.")

You might also like