Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

1.

2Write a Python program to draw a scatter plot with empty circles taking a random distribution in X
and Y and plotted against each other.

import matplotlib.pyplot as plt


import numpy as np
# Generate random data for X and Y
np.random.seed(0)
x = np.random.rand(50)
y = np.random.rand(50)
# Create the scatter plot with empty circles
plt.scatter(x, y, facecolors='none', edgecolors='b')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Scatter Plot with Empty Circles')
plt.show()

2. Write a Python program to draw a scatter plot using random distributions to generate balls of
different sizes.

import matplotlib.pyplot as plt


import numpy as np
# Generate random data for X, Y, and sizes
np.random.seed(0)
x = np.random.rand(50)
y = np.random.rand(50)
sizes = np.random.randint(10, 100, 50) # Random sizes between 10 and 100
# Create the scatter plot with different-sized balls
plt.scatter(x, y, s=sizes)
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Scatter Plot with Different-Sized Balls')
plt.show()

3. Write a Python program to draw a scatter plot comparing two subject marks of Mathematics
and Science. Use marks of 10 students.
Sample data:math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]science_marks = [35, 79, 79, 48,
100, 88, 32, 45, 20, 30]marks_range
= [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

import matplotlib.pyplot as plt


# Sample data
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# Create scatter plot
plt.scatter(marks_range, math_marks, label='Math marks', color='r')
plt.scatter(marks_range, science_marks, label='Science marks', color='g')
# Add labels and title
plt.title('Scatter Plot')
plt.xlabel('Marks Range')
plt.ylabel('Marks Scored')
plt.legend()
# Show plot
plt.show()

4. Write a Python script to concatenate following dictionaries


to create a new one. Sample Dictionary : dic1={1:10,
2:20} dic2={3:30, 4:40} dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

dic1 = {1: 10, 2: 20}


dic2 = {3:30, 4:40}
dic3 = {5:50,6:60}
result = {**dic1, **dic2, **dic3}
print(result)

5. Write a Python script to check whether a given key already exists in a dictionary.

def check_key(dictionary, key):


if key in dictionary:
print(f"The key {key} exists in the dictionary.")
else:
print(f"The key {key} does not exist in the dictionary.")
# Test the function
dictionary = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
key_to_check = 3
check_key(dictionary, key_to_check)

6. Write a Python script to generate and print a dictionary that contains a number (between 1 and
n) in the form (x, x*x).Sample Dictionary
( n = 5) : Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

def generate_dict(n):
return {x: x*x for x in range(1, n+1)}
# Test the function
n=5
print(generate_dict(n))

7. Write a Python program to remove a key from a dictionary


def remove_key(dictionary, key):
if key in dictionary:
del dictionary[key]
print(f"Removed key {key} from the dictionary.")
else:
print(f"The key {key} does not exist in the dictionary.")
return dictionary
# Test the function
dictionary = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
key_to_remove = 3
new_dictionary = remove_key(dictionary, key_to_remove)
print(new_dictionary)
8. Write a Python program to map two lists into a dictionary.

def map_lists_to_dict(keys, values):


return dict(zip(keys, values))
# Test the function
keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3, 4]
dictionary = map_lists_to_dict(keys, values)
print(dictionary)

9. Write a Python program to print all unique values in a dictionary

Sample Data : [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"},
{"V":"S009"},{"VIII":"S007"}]
Expected Output : Unique Values: {'S005', 'S002', 'S007', 'S001', 'S009'}
def print_unique_values(data):
unique_values = set(val for dic in data for val in dic.values())
print(f"Unique Values: {unique_values}")
# Test the function
data = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"},
{"V":"S009"},{"VIII":"S007"}]
print_unique_values(data)

10. Write a Python program to create a dictionary from a string. Note: Track the count of the
letters from the string.

def string_to_dict(s):
return {char: s.count(char) for char in set(s)}
# Test the function
s = "hello world"
print(string_to_dict(s))

11. Write a program that takes a sentence as an input parameter where each word in the sentence
is separated by a space. Then replace each blank with a hyphen and then print the modified
sentence.

def replace_spaces_with_hyphens(sentence):
modified_sentence = sentence.replace(' ', '-')
print(modified_sentence)
# Test the function
sentence = "This is a test sentence."
replace_spaces_with_hyphens(sentence)
12. Write a program to randomly select 10 integer elements from range 100 to 200 and find the
smallest among all.

import random
def find_smallest_random():
numbers = random.sample(range(100, 201), 10)
print(f"Randomly selected numbers: {numbers}")
smallest = min(numbers)
print(f"Smallest number: {smallest}")
# Run the function
find_smallest_random()

13. Create a dictionary of 5 countries with their currency details and display them.

Print as below
First line
Second line
Third Line
def create_country_currency_dict():
country_currency = {
"USA": "Dollar",
"UK": "Pound Sterling",
"Japan": "Yen",
"India": "Rupee",
"Australia": "Australian Dollar"
}
print("First line: USA, Currency: " + country_currency["USA"])
print("Second line: UK, Currency: " + country_currency["UK"])
print("Third line: Japan, Currency: " + country_currency["Japan"])
# Run the function
create_country_currency_dict()

14. Declare complex number , find data type, real part, imaginary part, complex conjugate,
absolute value of a number

def complex_number_operations():
# Declare a complex number
num = 3 + 4j
# Find and print data type
print(f"Data type: {type(num)}")
# Find and print real part
print(f"Real part: {num.real}")
# Find and print imaginary part
print(f"Imaginary part: {num.imag}")
# Find and print complex conjugate
print(f"Complex conjugate: {num.conjugate()}")
# Find and print absolute value
print(f"Absolute value: {abs(num)}")
# Run the function
complex_number_operations()

15. Change string hello to help ,remove white spaces before word if s=” hello ”

def modify_string(s):
s = s.strip() # Remove leading and trailing white spaces
s = s.replace('hello', 'help') # Replace 'hello' with 'help'
print(s)
# Test the function
s = " hello "
modify_string(s)

16. Write a program to randomly select 10 integer elements from range 100 to 200 and find the
smallest among all.

import random
def find_smallest_random():
numbers = random.sample(range(100, 201), 10)
print(f"Randomly selected numbers: {numbers}")
smallest = min(numbers)
print(f"Smallest number: {smallest}")
# Run the function
find_smallest_random()

17. Swap first & last letter of a string

def swap_first_last(s):
if len(s) < 2:
return s
return s[-1] + s[1:-1] + s[0]
# Test the function
s = "hello"
print(swap_first_last(s))

18. Find if substring is present in string or not

def is_substring_present(s, substring):


return substring in s
# Test the function
s = "hello world"
substring = "world"
print(is_substring_present(s, substring))
19. Write a program that takes a sentence as an input parameter where each word in the sentence
is separated by a space. Then replace each blank with a hyphen and then print the modified
sentence.

def replace_spaces_with_hyphens(sentence):
modified_sentence = sentence.replace(' ', '-')
print(modified_sentence)
# Test the function
sentence = "This is a test sentence."
replace_spaces_with_hyphens(sentence)

20. WAPP to test whether string is palindrome or not

def is_palindrome(s):
return s == s[::-1]
# Test the function
s = "radar"
print(is_palindrome(s))

21. WAP to capitalize the first character of each words from a given sentence (example: all the
best All The Best)

def capitalize_first_char(sentence):
capitalized_sentence = ' '.join(word.capitalize() for word in sentence.split())
print(capitalized_sentence)
# Test the function
sentence = "all the best"
capitalize_first_char(sentence)

22. WAP to count the frequency of occurrence of a given character in a given line of text

def count_char_frequency(text, char):


frequency = text.count(char)
print(f"Frequency of '{char}' in the text: {frequency}")
# Test the function
text = "hello world"
char = "l"
count_char_frequency(text, char)

23. Create a dictionary of 4 states with their capital details & add one more pair to the same

def create_state_capital_dict():
state_capital = {
"California": "Sacramento",
"Texas": "Austin",
"Florida": "Tallahassee",
"New York": "Albany"
}
# Add one more pair
state_capital["Washington"] = "Olympia"
print(state_capital)
# Run the function
create_state_capital_dict()

24. To count number digits, special symbols from the given sentence. Also count number of
vowels and consonants

def count_elements(sentence):
digits = sum(c.isdigit() for c in sentence)
special_symbols = sum(c.isalnum() == False and c.isspace() == False for c in sentence)
vowels = sum(c.lower() in 'aeiou' for c in sentence)
consonants = sum(c.isalpha() and c.lower() not in 'aeiou' for c in sentence)
print(f"Number of digits: {digits}")
print(f"Number of special symbols: {special_symbols}")
print(f"Number of vowels: {vowels}")
print(f"Number of consonants: {consonants}")
# Test the function
sentence = "Hello, World! 123"
count_elements(sentence)

25. Write a program to accept any string up to 15 characters. Display the elements of string with
their element nos

def display_elements():
s = input("Enter a string (up to 15 characters): ")
if len(s) > 15:
print("The string is too long.")
else:
for i, char in enumerate(s, start=1):
print(f"Element {i}: {char}")
# Run the function
display_elements()

26. Create a Numpy array filled with all ones

import numpy as np
def create_ones_array(shape):
ones_array = np.ones(shape)
print(ones_array)
# Test the function
shape = (3, 3)
create_ones_array(shape)

27. Check whether a Numpy array contains a specified row

import numpy as np
def contains_row(matrix, row):
return any((matrix == row).all(1))
# Test the function
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
row = np.array([4, 5, 6])
print(contains_row(matrix, row))
28. Compute mathematical operations on Array, Add & Multiply two matrices

import numpy as np
def matrix_operations():
# Create two matrices
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
# Add the matrices
sum_matrix = np.add(matrix1, matrix2)
print(f"Sum of matrices:\n{sum_matrix}")
# Multiply the matrices
product_matrix = np.dot(matrix1, matrix2)
print(f"Product of matrices:\n{product_matrix}")
# Run the function
matrix_operations()

29. Find the most frequent value in a NumPy array

import numpy as np
from scipy import stats
def most_frequent_value(arr):
mode = stats.mode(arr)
if np.isscalar(mode.mode):
print(f"Most frequent value: {mode.mode}")
else:
print(f"Most frequent value: {mode.mode[0]}")
# Test the function
arr = np.array([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
most_frequent_value(arr)

30. Flatten a 2d numpy array into 1d array

import numpy as np
def flatten_array(arr):
flattened_array = arr.flatten()
print(flattened_array)
# Test the function
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
flatten_array(arr)

31. Calculate the sum of all columns in a 2D NumPy array

import numpy as np
def sum_columns(arr):
column_sums = np.sum(arr, axis=0)
print(column_sums)
# Test the function
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
sum_columns(arr)

32. Calculate the average, variance and standard deviation in Python using NumPy

import numpy as np
def calculate_statistics(arr):
average = np.mean(arr)
variance = np.var(arr)
standard_deviation = np.std(arr)
print(f"Average: {average}")
print(f"Variance: {variance}")
print(f"Standard Deviation: {standard_deviation}")
# Test the function
arr = np.array([1, 2, 3, 4, 5])
calculate_statistics(arr)

33. Insert a space between characters of all the elements of a given NumPy array ['Python' 'is'
'easy'] ['P y t h o n' 'i s' 'e a s y']

import numpy as np
def insert_spaces(arr):
spaced_arr = [' '.join(list(word)) for word in arr]
print(spaced_arr)
# Test the function
arr = np.array(['Python', 'is', 'easy'])
insert_spaces(arr)

34. Plot line graph from NumPy array

import numpy as np
import matplotlib.pyplot as plt
# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
# Plot the array
plt.plot(arr)
plt.title('Line graph from NumPy array')
plt.xlabel('Index')
plt.ylabel('Value')
plt.show()

35. WAP to Reverse a Number

def reverse_number(n):
reversed_number = int(str(n)[::-1])
return reversed_number
# Test the function
n = 12345
print(f"Original number: {n}")
print(f"Reversed number: {reverse_number(n)}")

36. WAP to read number N and print natural numbers summation pattern

def print_summation_pattern(n):
for i in range(1, n+1):
print(' + '.join(str(j) for j in range(1, i+1)), "=", sum(range(1, i+1)))
# Test the function
N=5
print_summation_pattern(N)

37. WAP to determine all Pythagorean triplets

def find_pythagorean_triplets(limit):
triplets = []
for a in range(1, limit+1):
for b in range(a, limit+1):
c = (a*2 + b2)*0.5
if c.is_integer() and c <= limit:
triplets.append((a, b, int(c)))
return triplets
# Test the function
limit = 20
print(f"Pythagorean triplets up to {limit}:")
for triplet in find_pythagorean_triplets(limit):
print(triplet)

38. WAP, You are given a number A which contains only digits 0's and 1's. Your task is to make
all digits same by just flipping one digit (i.e.0 to 1 or 1 to 0 ) only. If it is possible to make all
the digits same by just flipping one digit then print 'YES' else print 'NO'.

def can_flip_to_same_digits(A):
digit_str = str(A)
zero_count = digit_str.count('0')
one_count = digit_str.count('1')

if zero_count == 1 or one_count == 1:
print('YES')
else:
print('NO')
# Test the function
A = 101
can_flip_to_same_digits(A)

39. Given a list A of N distinct integer numbers, you can sort the list by moving an element to the
end of the list. Find the minimum number of moves required to sort the list using this method
in ascending order
def min_moves_to_sort(A):
sorted_A = sorted(A)
i=j=0
max_len = 0
while i < len(A) and j < len(A):
if A[i] == sorted_A[j]:
i += 1
j += 1
max_len = max(max_len, j)
else:
i += 1
return len(A) - max_len
# Test the function
A = [1, 3, 2, 4, 5]
print(f"Minimum number of moves to sort the list: {min_moves_to_sort(A)}")

40. WAP to print following pattern

1\n
22\n
333\n
4444\n
55555\n
666666
def print_pattern(n):
for i in range(1, n+1):
print(str(i) * i)
# Test the function
print_pattern(6)

41. Convert two lists into a dictionary

def lists_to_dict(keys, values):


return dict(zip(keys, values))
# Test the function
keys = ['a', 'b', 'c']
values = [1, 2, 3]
print(lists_to_dict(keys, values))

42. Check how many times a given number can be divided by 6 before it is less than or equal to
10.

def count_divisions_by_six(n):
count = 0
while n > 10:
n /= 6
count += 1
return count
# Test the function
n = 720
print(f"Number of times {n} can be divided by 6 before it is less than or equal to 10:
{count_divisions_by_six(n)}")

43. Python program to read a file and Capitalize the first letter of every word in the file.

def capitalize_words_in_file(filename):
with open(filename, 'r') as file:
lines = file.readlines()
capitalized_lines = [' '.join(word.capitalize() for word in line.split()) for line in lines]
with open(filename, 'w') as file:
file.writelines(capitalized_lines)
# Test the function
# Please replace 'test.txt' with your actual file name
capitalize_words_in_file('q2.py')

44. Python program that reads a text file and counts number of times certain letter appears in the
text file.

def count_letter_in_file(filename, letter):


with open(filename, 'r',encoding='utf-8') as file:
text = file.read()
return text.count(letter)
# Test the function
# Please replace 'test.txt' with your actual file name
filename = 'q2.py'
letter = 'p'
print(f"Number of times '{letter}' appears in {filename}:
{count_letter_in_file(filename, letter)}")

45. Write a program to write content to file & append data to file.

def write_and_append_to_file(filename, initial_content, additional_content):


# Write initial content to the file
with open(filename, 'w') as file:
file.write(initial_content)
# Append additional content to the file
with open(filename, 'a') as file:
file.write(additional_content)
# Test the function
# Please replace 'test.txt' with your actual file name
filename = 'test.txt'
initial_content = 'This is the initial content.\n'
additional_content = 'This is the additional content.\n'
write_and_append_to_file(filename, initial_content, additional_content)
46. Python program to read the contents of a file

def read_file_contents(filename):
with open(filename, 'r') as file:
contents = file.read()
return contents
# Test the function
# Please replace 'test.txt' with your actual file name
filename = 'test.txt'
print(read_file_contents(filename))

47. Copy the contents from one file to another ‘

def copy_file_contents(source_filename, destination_filename):


with open(source_filename, 'r') as source_file:
contents = source_file.read()
with open(destination_filename, 'w') as destination_file:
destination_file.write(contents)
# Test the function
# Please replace 'source.txt' and 'destination.txt' with your actual file names
source_filename = 'source.txt'
destination_filename = 'destination.txt'
copy_file_contents(source_filename, destination_filename)

48. WAP to accept name and roll number of students and store it in file. Read and display the
stored data. Also check if file exists or not
import os

def store_and_display_student_data(filename):
# Accept student data
name = input("Enter student's name: ")
roll_number = input("Enter student's roll number: ")
# Store student data in file
with open(filename, 'w') as file:
file.write(f"Name: {name}\nRoll Number: {roll_number}\n")
# Check if file exists
if not os.path.exists(filename):
print(f"File {filename} does not exist.")
return
# Read and display the stored data
with open(filename, 'r') as file:
contents = file.read()
print(f"Stored data:\n{contents}")
# Test the function
# Please replace 'student_data.txt' with your actual file name
filename = 'student_data.txt'
store_and_display_student_data(filename)

49. WAP to copy contents of 1 file to another Let user specify name of source and destination
files
def copy_file_contents():
# Get source and destination filenames from user
source_filename = input("Enter the name of the source file: ")
destination_filename = input("Enter the name of the destination file: ")
# Copy contents from source file to destination file
with open(source_filename, 'r') as source_file:
contents = source_file.read()
with open(destination_filename, 'w') as destination_file:
destination_file.write(contents)
print(f"Contents of {source_filename} have been copied to {destination_filename}.")
copy_file_contents()

50. Python program to read file word by word

def read_file_word_by_word(filename):
with open(filename, 'r') as file:
for line in file:
for word in line.split():
print(word)
# Test the function
# Please replace 'test.txt' with your actual file name
filename = 'test.txt'
read_file_word_by_word(filename)

51. Python program to read character by character from a file

def read_file_char_by_char(filename):
with open(filename, 'r') as file:
while True:
char = file.read(1)
if not char:
break
print(char)
# Test the function
# Please replace 'test.txt' with your actual file name
filename = 'test.txt'
read_file_char_by_char(filename)

52. Python – Get number of characters, words, spaces and lines in a file

def get_file_stats(filename):
num_chars = num_words = num_spaces = num_lines = 0
with open(filename, 'r') as file:
for line in file:
num_lines += 1
num_chars += len(line)
num_words += len(line.split())
num_spaces += line.count(' ')
print(f"Number of characters: {num_chars}")
print(f"Number of words: {num_words}")
print(f"Number of spaces: {num_spaces}")
print(f"Number of lines: {num_lines}")
# Test the function
# Please replace 'test.txt' with your actual file name
filename = 'test.txt'
get_file_stats(filename)
53. Make your exception class “InvalidMarks” which is thrown when marks obtained by student
exceeds 100

class InvalidMarks(Exception):
pass
def check_marks(marks):
if marks > 100:
raise InvalidMarks("Marks cannot exceed 100.")
# Test the function
# Please replace 105 with the actual marks obtained by the student
marks = 105
try:
check_marks(marks)
except InvalidMarks as e:
print(e)

54. WAP that accepts the values of a, b, c and d. Calculate and display ((a+d) + (b*c))/ (b*d).
create user defined exception to display proper message when value of (b*d) is zero

class DivisionByZeroError(Exception):
pass
def calculate_expression(a, b, c, d):
if b * d == 0:
raise DivisionByZeroError("The value of (b*d) cannot be zero.")
return ((a + d) + (b * c)) / (b * d)
# Test the function
# Please replace 1, 2, 3, 4 with your actual values for a, b, c, d
a, b, c, d = 1, 2, 3, 0
try:
result = calculate_expression(a, b, c, d)
print(result)
except DivisionByZeroError as e:
print(e)

55. Ask user to input an age. Raise an exception for age less than 18 , print message “ age is not
valid ” & “age is valid ” if age entered is more than 18

class InvalidAgeError(Exception):
pass
def check_age():
age = int(input("Enter your age: "))
if age < 18:
raise InvalidAgeError("Age is not valid.")
else:
print("Age is valid.")
# Test the function
try:
check_age()
except InvalidAgeError as e:
print(e)

56. 48Handle the FileNotFoundError exception

def read_file(filename):
try:
with open(filename, 'r') as file:
print(file.read())
except FileNotFoundError:
print(f"The file '{filename}' does not exist.")
# Test the function
# Please replace 'non_existent_file.txt' with your actual file name
filename = 'non_existent_file.txt'
read_file(filename)

57. Raise a TypeError if x is not a string

def check_string(x):
if not isinstance(x, str):
raise TypeError("The input must be a string.")
# Test the function
# Please replace 123 with your actual input
x = 123
try:
check_string(x)
except TypeError as e:
print(e)

58. Create class Complex , define two methods init to take real & imaginary number & method
add to add real & imaginary part of complex number . print addition of real part & addition of
imaginary part.

class Complex:
def _init_(self, real, imag):
self.real = real
self.imag = imag
def add(self, other):
real_sum = self.real + other.real
imag_sum = self.imag + other.imag
return real_sum, imag_sum
# Test the class
# Please replace 1, 2, 3, 4 with your actual real and imaginary numbers
c1 = Complex(1, 2)
c2 = Complex(3, 4)
real_sum, imag_sum = c1.add(c2)
print(f"Addition of real parts: {real_sum}")
print(f"Addition of imaginary parts: {imag_sum}")
59. Create class Triangle, Create object from it . The objects will have 3 attributes named a,b,c
that represent sides of triangle .Triangle class will have two methods init method to initialize
the sides & method to calculate perimeter of triangle from its sides . Perimeter of triangle
should be printed from outside the class

class Triangle:
def _init_(self, a, b, c):
self.a = a
self.b = b
self.c = c
def calculate_perimeter(self):
return self.a + self.b + self.c
# Test the class
# Please replace 3, 4, 5 with your actual side lengths
t = Triangle(3, 4, 5)
perimeter = t.calculate_perimeter()
print(f"Perimeter of the triangle: {perimeter}")

60. Python program to append ,delete and display elements of a list using classe

class MyList:
def _init_(self):
self.my_list = []
def append_element(self, element):
self.my_list.append(element)
def delete_element(self, element):
if element in self.my_list:
self.my_list.remove(element)
def display_elements(self):
return self.my_list
# Test the class
my_list = MyList()
my_list.append_element(1)
my_list.append_element(2)
my_list.append_element(3)
print(f"List after appending elements: {my_list.display_elements()}")
my_list.delete_element(2)
print(f"List after deleting an element: {my_list.display_elements()}")

61. Write a program to create a class which performs basic calculator operations

class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
if b == 0:
return "Error: Division by zero is not allowed."
return a / b
# Test the class
calculator = Calculator()
print(f"Addition: {calculator.add(5, 3)}")
print(f"Subtraction: {calculator.subtract(5, 3)}")
print(f"Multiplication: {calculator.multiply(5, 3)}")
print(f"Division: {calculator.divide(5, 3)}")

62. Write a Python class named Student with two attributes student_id, student_name. Add a new
attribute student_class. Create a function to display the entire attribute and their values in
Student class.

class Student:
def _init_(self, student_id, student_name, student_class):
self.student_id = student_id
self.student_name = student_name
self.student_class = student_class
def display_attributes(self):
return f"ID: {self.student_id}, Name: {self.student_name}, Class: {self.student_class}"
# Test the class
# Please replace 1, 'John Doe', '10th Grade' with your actual student details
student = Student(1, 'John Doe', '10th Grade')
print(student.display_attributes())

63. Write a Python class to reverse a string word by word.

class StringReverser:
def reverse_words(self, s):
return ' '.join(reversed(s.split()))
# Test the class
# Please replace 'Hello World' with your actual string
string_reverser = StringReverser()
print(string_reverser.reverse_words('Hello World'))

64. Write a Python class which has two methods get_String and print_String. get_String accept a
string from the user and print_String print the string in upper case

class StringHandler:
def _init_(self):
self.str1 = ""
def get_string(self, user_input):
self.str1 = user_input
def print_string(self):
print(self.str1.upper())
# Test the class
# Please replace 'Hello World' with your actual string
string_handler = StringHandler()
string_handler.get_string('Hello World')
string_handler.print_string()
65. Write a Python class named Circle constructed by a radius and two methods which will
compute the area and the perimeter of a circle.

import math
class Circle:
def _init_(self, radius):
self.radius = radius
def compute_area(self):
return math.pi * (self.radius ** 2)
def compute_perimeter(self):
return 2 * math.pi * self.radius
# Test the class
# Please replace 5 with your actual radius
circle = Circle(5)
print(f"Area: {circle.compute_area()}")
print(f"Perimeter: {circle.compute_perimeter()}")

66. Write a Python program to create a Vehicle class with max_speed and mileage instance
attributes. Create a child class Bus that will inherit all of the variables and methods of the
Vehicle class

class Vehicle:
def _init_(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
class Bus(Vehicle):
pass
# Test the classes
# Please replace 120, 10 with your actual max speed and mileage
bus = Bus(120, 10)
print(f"Max Speed: {bus.max_speed}")
print(f"Mileage: {bus.mileage}")

67. Load a dataset using pandas : perform basic operations , data visualization using
matplotlib ,seaborn etc

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Load the dataset
# Please replace 'your_dataset.csv' with your actual dataset file path
df = pd.read_csv('ds.csv')
# Perform basic operations
print(df.head()) # Print the first 5 rows
print(df.describe()) # Generate descriptive statistics
# Data visualization using matplotlib
df.hist(figsize=(10, 10)) # Plot histograms for all columns
plt.show()
# Data visualization using seaborn
sns.pairplot(df) # Plot pairwise relationships in the dataset
plt.show()
68. WAPP to push all zeros to the end of a given list. The order of elements should not change:

Input: 0 2 3 4 6 7 9 0
Output:2 3 4 6 7 9 0 0
def push_zeros_to_end(lst):
result = [i for i in lst if i != 0] + [i for i in lst if i == 0]
return result
# Test the function
# Please replace [0, 2, 3, 4, 6, 7, 9, 0] with your actual list
print(push_zeros_to_end([0, 2, 3, 4, 6, 7, 9, 0]))

69. Write a program that accepts a comma separated sequence of words as input and prints the
words in a comma separated sequence after sorting them alphabetically.
Input: without, hello,bag, world
Output: bag,hello,without,world
def sort_words(input_words):
words = [word.strip() for word in input_words.split(',')]
words.sort()
return ','.join(words)
# Test the function
# Please replace 'without, hello, bag, world' with your actual sequence of words
print(sort_words('without, hello, bag, world'))

70. WAP that calculates & prints value accoridng to given formula:

Q=Square root of [(2*C*D)/H]


C is 50 , H is 30. D is variable whose values should be input to program in comma
separated sequence.
Input: 100,150,180
Output:18,22,24
import math
def calculate_values(D_values):
C = 50
H = 30
Q_values = [round(math.sqrt((2*C*D)/H)) for D in D_values]
return Q_values
# Test the function
# Please replace [100, 150, 180] with your actual D values
print(calculate_values([100, 150, 180]))

71. With given list L of integers , write a program that prints this L after removing duplicate
values with original order preserved.
Input: 12 24 35 24 88 120 155 88 120 155
Output: 12 24 35 88 120 155
def remove_duplicates(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
# Test the function
# Please replace [12, 24, 35, 24, 88, 120, 155, 88, 120, 155] with your actual list
print(remove_duplicates([12, 24, 35, 24, 88, 120, 155, 88, 120, 155]))

72. Given ab integer number n , define function named printDict(),which can print a dictionary
where keys are numbers between 1 to n (both included) and values are square of keys .
Function printDict(), does not take any arguments.

def printDict():
n = int(input("Enter a number: "))
d = {i: i**2 for i in range(1, n+1)}
print(d)
# Test the function
printDict()

73. Python program to find the sum of the digits of an integer using while loop

def sum_of_digits(n):
sum = 0
while n > 0:
digit = n % 10
sum += digit
n //= 10
return sum
# Test the function
# Please replace 12345 with your actual integer
print(sum_of_digits(12345))

74. Python program to generate the prime numbers from 1 to N

def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
def generate_primes(N):
primes = []
for num in range(1, N + 1):
if is_prime(num):
primes.append(num)
return primes
N = int(input("Enter the value of N: "))
prime_numbers = generate_primes(N)
print("Prime numbers from 1 to", N, "are:", prime_numbers)

75. Python program to print the numbers from a given number n till 0 using recursion

def print_numbers(n):
if n >= 0:
print(n)
print_numbers(n - 1)
# Test the function
# Please replace 10 with your actual number
print_numbers(10)

76. Write a Python function student_data () which will print the id of a student (student_id). If the
user passes an argument student_name or student_class the function will print the student
name and class.

def student_data(student_id, student_name=None, student_class=None):


print("Student ID:", student_id)
if student_name:
print("Student Name:", student_name)
if student_class:
print("Student Class:", student_class)
student_data(1, 'John Doe', '10th Grade')
student_data(2, 'Jane Doe')
student_data(3)

77. Write a Python class to convert a roman numeral to an integer


class RomanConverter:
def _init_(self):
self.roman_to_int = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
def convert_to_int(self, roman_numeral):
result = 0
prev_value = 0
for char in roman_numeral[::-1]:
value = self.roman_to_int[char]
if value < prev_value:
result -= value
else:
result += value
prev_value = value
return result
# Example usage
converter = RomanConverter()
roman_numeral = 'XLII'
integer_value = converter.convert_to_int(roman_numeral)
print(integer_value)

78. Write a Python class to get all possible unique subsets from a set of distinct integers

class SubsetGenerator:
def _init_(self, nums):
self.nums = nums
def generate_subsets(self):
subsets = [[]]
for num in self.nums:
subsets += [subset + [num] for subset in subsets]
return subsets
# Example usage
nums = [1, 2, 3]
generator = SubsetGenerator(nums)
all_subsets = generator.generate_subsets()
print(all_subsets)

79. Write a Python class to find a pair of elements (indices of the two numbers) from a given
array whose sum equals a specific target number

class PairFinder:
def find_pair(self, nums, target):
num_dict = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_dict:
return [num_dict[complement], i]
num_dict[num] = i
return None
# Example usage
nums = [2, 7, 11, 15]
target = 9
pair_finder = PairFinder()
result = pair_finder.find_pair(nums, target)
if result:
print(f"Pair found at indices {result[0]} and {result[1]}")
else:
print("No pair found")

80. Write a Python class to implement pow(x, n).

class Power:
def _init_(self, x, n):
self.x = x
self.n = n
def calculate(self):
return self.x ** self.n
# Test the class
# Please replace 2 and 3 with your actual x and n
p = Power(2, 3)
print(p.calculate())

81. Write a NumPy program to convert the values of Centigrade degrees into Fahrenheit degrees
and vice versa. Values are stored into a NumPy array. Sample Array [0, 12, 45.21, 34, 99.91]

import numpy as np
def convert_temperatures(temps, scale_to):
if scale_to.lower() == 'fahrenheit':
return np.array(temps) * 9/5 + 32
elif scale_to.lower() == 'centigrade':
return (np.array(temps) - 32) * 5/9
else:
return "Invalid scale_to argument. It should be either 'Fahrenheit' or 'Centigrade'."
# Test the function
# Please replace [0, 12, 45.21, 34, 99.91] with your actual temperatures and 'Fahrenheit' with
your actual scale_to
print(convert_temperatures([0, 12, 45.21, 34, 99.91], 'Fahrenheit'))

82. Write a NumPy program to find the set difference of two arrays. The set difference will return
the sorted, unique values in array1 that are not in array2

import numpy as np
def set_difference(array1, array2):
return np.setdiff1d(array1, array2)
# Test the function
# Please replace [0, 10, 20, 40, 60, 80] and [10, 30, 40, 50, 70] with your actual arrays
print(set_difference([0, 10, 20, 40, 60, 80], [10, 30, 40, 50, 70]))

83. Write a Pandas program to create and display a DataFrame from a specified dictionary data
which has the index labels. Go to the editor Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'], 'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j'

import pandas as pd
import numpy as np
exam_data = {
'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin',
'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']
}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data, index=labels)
print(df)

84. Write a Pandas program to get the first 3 rows of a given DataFrame

import pandas as pd
# Create a dictionary of data
data = {
'Name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'Age': [28, 24, 35, 32, 30],
'City': ['New York', 'Paris', 'Berlin', 'London', 'Sydney']
}

# Create a DataFrame from the dictionary


df = pd.DataFrame(data)
# Get the first 3 rows
print(df.head(3))
85. Write a Pandas program to select the 'name' and 'score' columns from the following
DataFrame.

import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [85, 90, 88, 92, 87],
'age': [28, 24, 35, 32, 30]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Select 'name' and 'score' columns
selected_columns = df[['name', 'score']]
print(selected_columns)

86. Write a Pandas program to select the specified columns and rows from a given data frame.

import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James', 'Michael', 'Sarah', 'Jessica', 'Jacob', 'Emma'],
'score': [85, 90, 88, 92, 87, 95, 78, 88, 92, 85],
'age': [28, 24, 35, 32, 30, 27, 29, 31, 23, 25]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Select 'name' and 'score' columns for the 2nd, 4th, and 6th rows
selected_data = df[['name', 'score']].iloc[[1, 3, 5]]
print(selected_data)

87. Write a Pandas program to select the rows where the number of attempts in the examination is
greater than 2.

import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [85, 90, 88, 92, 87],
'attempts': [3, 2, 4, 3, 5]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Select rows where the number of attempts is greater than 2
selected_rows = df[df['attempts'] > 2]
print(selected_rows)

88. Write a Pandas program to count the number of rows and columns of a DataFrame.

import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [85, 90, 88, 92, 87],
'attempts': [3, 2, 4, 3, 5]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Count the number of rows and columns
num_rows = len(df)
num_cols = len(df.columns)
print("Number of Rows: ", num_rows)
print("Number of Columns: ", num_cols)

89. Write a Pandas program to select the rows the score is between 15 and 20 (inclusive).

import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [15, 20, 14, 18, 16],
'attempts': [3, 2, 1, 3, 2]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Select rows where the score is between 15 and 20
selected_rows = df[(df['score'] >= 15) & (df['score'] <= 20)]
print(selected_rows)

90. Write a Pandas program to select the rows where number of attempts in the examination is
less than 2 and score greater than 15

import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [18, 20, 14, 22, 16],
'attempts': [1, 2, 1, 3, 1]
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Select rows where the number of attempts is less than 2 and score is greater than 15
selected_rows = df[(df['attempts'] < 2) & (df['score'] > 15)]
print(selected_rows)

91. Write a Pandas program to append a new row 'k' to data frame with given values for each
column. Now delete the new row and return the original DataFrame

import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [18, 20, 14, 22, 16],
'attempts': [1, 2, 1, 3, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'yes']
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Append a new row 'k' with given values
df.loc['k'] = ['Suresh', 15.5, 1, 'yes']
# Print DataFrame after appending
print("After appending a new row:\n", df)
# Delete the new row and return the original DataFrame
df = df.drop('k')
# Print DataFrame after deleting the new row
print("After deleting the new row:\n", df)

92. Write a Pandas program to sort the DataFrame first by 'name' in descending order, then by
'score' in ascending order.

import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [18, 20, 14, 22, 16],
'attempts': [1, 2, 1, 3, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'yes']
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Sort the DataFrame first by 'name' in descending order, then by 'score' in ascending order
df = df.sort_values(by=['name', 'score'], ascending=[False, True])
print(df)

93. Write a Pandas program to replace the 'qualify' column contains the values 'yes' and 'no' with
True and False.

import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [18, 20, 14, 22, 16],
'attempts': [1, 2, 1, 3, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'yes']
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Replace 'yes' and 'no' with True and False in 'qualify' column
df['qualify'] = df['qualify'].map({'yes': True, 'no': False})
print(df)
94. Write a Pandas program to set a given value for particular cell in DataFrame using index
value.

import pandas as pd
# Create a dictionary of data
data = {
'name': ['John', 'Anna', 'Peter', 'Linda', 'James'],
'score': [18, 20, 14, 22, 16],
'attempts': [1, 2, 1, 3, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'yes']
}
# Create a DataFrame from the dictionary
df = pd.DataFrame(data)
# Set a given value for a particular cell using the index value
df.at[1, 'score'] = 25
print(df)

You might also like