Python Coding Questions
Python Coding Questions
If Statement:
1.Write a Python program that checks if a number is positive.
2.Write a Python program that checks if a given string is empty.
3.Write a Python program that determines if a number is positive, negative, or zero using
only if statements and no elif or else.
4.Write a Python program that checks if a number is a multiple of both 3 and 5.
5.Write a Python program that determines if a given number is a perfect square.
6.Write a Python program that checks if a number is divisible by both 2 and 3.
7.Write a Python program that determines if a number is a perfect cube.
8.Write a Python program that checks if a given number is a multiple of 4.
If-Else Statement:
1.Write a Python program that checks if a number is positive.
2.Write a Python program that checks if a given string is empty.
3.Write a Python program that checks if a given year is a leap year.
4.Write a Python program that checks if a given character is a vowel or a consonant.
5.Write a Python program that checks if a given year is a century year (ending in '00').
6.Write a Python program that checks if a given number is prime.
7.Write a Python program that checks if a person is eligible to vote based on their age.
8.Write a Python program that determines if a given number is zero or non-zero.
9.Write a Python program that checks if a number is positive or non-positive (including zero).
10.Write a Python program that compares two numbers and prints the largest one.
11.Write a Python program that checks if a given character is a letter or not.
12.Write a Python program that checks if a number is even or non-even (odd).
13.Write a Python program that finds and prints the smallest of three numbers.
14.Write a Python program that checks if a year is a leap year or not.
15.Write a Python program that checks if a number is a multiple of 5 or not.
16.Write a Python program that classifies a number as positive, negative, or zero using nested
if-else statements.
17.Write a Python program that checks if a number is a multiple of both 2 and 3.
18.Write a Python program that checks if a number is a perfect square.
Page 1 of 70
19.Write a Python program to check if a given string is a palindrome.
20.Write a Python program to check if a character is a vowel or a consonant.
21.Write a Python program that finds and prints the largest of four numbers.
22.Write a Python program that takes two numbers as input and determines the sign of their
difference.
23.Write a Python program that checks if a given year is a leap year using an alternative
method.
24.Write a Python program that checks if a number is a multiple of 7 or not.
25.Write a Python program that checks if a character is a vowel or not (case-insensitive).
26.Write a Python program that calculates and prints the absolute value of a given number.
If-Elif-Else Statement:
1.Write a Python program that determines the sign (positive, negative, or zero) of a number.
2.Write a Python program that classifies a number as positive, negative, or zero using chained
if-else statements.
3.Write a Python program that calculates and prints the grade based on a given score.
4.Write a Python program that compares two numbers and prints whether the first number is
greater, equal to, or less than the second number.
5.Write a Python program that classifies a person's age into categories: child, teenager, adult,
or senior.
6.Write a Python program that converts a temperature in Celsius to Fahrenheit or vice versa
based on user input.
7.Write a simple calculator program that performs basic arithmetic operations (addition,
subtraction, multiplication, division) based on user input.
8.Write a Python program that calculates and categorizes a person's Body Mass Index (BMI)
based on their weight and height.
9.Write a Python program for a simple "Guess the Number" game. Generate a random
number, and have the user guess it.
10.Write a Python program that checks whether a given year is a leap year or not.
11.Write a Python program that checks the strength of a user's password based on certain
criteria.
12.Write a Python program for a simple "Rock, Paper, Scissors" game where the user plays
against the computer.
13.Write a Python program that calculates the final price of an item after applying a discount
based on the purchase amount.
Page 2 of 70
14.Write a Python program that simulates an ATM machine, allowing users to check their
balance and withdraw money.
15.Write a Python program that greets the user differently based on the time of day.
16.Write a Python program that solves a quadratic equation of the form ax^2 + bx + c = 0 and
prints the solutions.
17.Write a Python program that calculates the final price of an item after applying a discount
coupon code.
18.Write a Python program that calculates and prints the grade based on a given score, but
also validates the input score.
19.Write a Python program that acts as a simple calculator and allows the user to choose the
operation (addition, subtraction, multiplication, division).
20.Write a Python program that determines the number of days in a given month.
21.Write a Python program that calculates a person's Body Mass Index (BMI) and categorizes
it into different categories (underweight, normal weight, overweight, obese).
22.Write a Python program that identifies a person's age group based on their age.
23.Write a Python program that converts letter grades (A, B, C, D, F) to their equivalent GPA
values.
24.Write a Python program that checks the type of a file based on its extension.
Nested If Statement:
1.Given x = 10 and y = 5, write a Python program to determine if x is greater than y. If x is
greater than y,check if it's also greater than 15 and print appropriate messages accordingly.
2.Write a Python program that takes a grade as input and prints the corresponding letter
grade. If the grade is less than 70, also print "You failed."
3.Write a Python program to check if a person is eligible for a credit card based on their age
and income.If the person is underage, print "You are underage." If they are of age but have an
income below $30,000, print "Your income is too low for a credit card."
4.Write a Python program to determine if a given number num is even or odd. If it's even,
check if it's greater than 10 and print appropriate messages.
5.Write a Python program that calculates the ticket price for a theme park based on age and
height. If a person isunder 12 years old and under 4 feet tall, their ticket price is $10. If they
are under 12 but 4 feet tall or taller,their ticket price is $15. For individuals 12 and older who
are 4 feet tall or taller, the ticket price is $20.
6.Write a Python program for user authentication. Ask the user to enter their username and
password. If both theusername and password are correct, print "Access granted." If the
username is correct but the password is incorrect,print "Incorrect password." If the username
is incorrect, print "Invalid username."
Page 3 of 70
7.Write a Python program for ordering food. Ask the user to select a type of food (e.g.,
"Burger" or "Pizza").If they choose "Burger," ask if they want fries. If they choose "Pizza,"
ask if they want extra cheese. Print their order with the additional items if chosen.
8.Write a Python program that takes an integer as input and checks if it's positive, negative, or
zero. If it's positive,check if it's even or odd. Print the appropriate messages.
9.Write a Python program that asks for a user's age and whether they have a driver's license.
If the user is 18 or older andhas a driver's license, print "You are eligible to drive." Otherwise,
print "You are not eligible to drive."
10.Write a Python program that checks if a person is eligible to vote. Ask for the person's age
and whether they are a citizen.If the person is at least 18 years old and a citizen, print "You
are eligible to vote." Otherwise, print "You are not eligible to vote."
11.Write a Python program that takes three numbers as input and prints them in ascending
order.
12.Write a Python program for a store that calculates discounts based on the purchase amount
and membership status. Ask theuser for the purchase amount and whether they have a
membership. If the purchase amount is greater than $100 and they havea membership, apply
a 20% discount. If the purchase amount is greater than $100 without a membership, apply a
10% discount. Otherwise, no discount is applied.
13.Write a Python program that classifies a character as a vowel, consonant, or neither. Ask
the user to enter a single character.If it's a vowel (a, e, i, o, u), print "Vowel." If it's a
consonant, print "Consonant." If it's neither (e.g., a digit or special character), print "Neither."
14.Write a Python program that recommends books based on the reader's age and genre
preference. Ask the user for their age andfavorite genre ("Mystery," "Fantasy," or "Science
Fiction"). Recommend different books based on their input.
15.Write a Python program that calculates the price of movie tickets based on age and time of
day. Ask the userfor their age and whether it's a matinee show (before 5 PM). If the person is
under 12 or over 65,they get a discount. Apply different pricing rules based on age and
showtime.
16.Write a Python program for a delivery service that calculates delivery charges based on
distance and order amount.Ask the user for the distance (in miles) and order amount. Apply
different charges based on the distance and order amount.
17.Write a Python program that calculates employee bonuses based on performance and years
of service. Ask the user for theemployee's performance rating (Excellent, Good, or Average)
and years of service. Calculate and print the bonus amount.
18.Write a Python program for a library that calculates late fees for borrowed books. Ask the
user for the number ofdays the book is overdue and the type of book (regular or reference).
Calculate and print the late fee.
19.Write a Python program that determines whether a student is eligible for a scholarship
based on their GPA and extracurricularactivities. Ask for the student's GPA and the number of
Page 4 of 70
extracurricular activities they are involved in. Award the scholarshipif GPA is above 3.5 and
they are involved in at least 3 activities.
20.Write a Python program that recommends clothing based on the weather temperature and
whether it's raining. Ask theuser for the temperature (in degrees Celsius) and whether it's
raining. Provide clothing recommendations accordingly.
21.Write a Python program that recommends a movie based on the user's preferences. Ask the
user for theirpreferred genre and age group, and provide movie recommendations
accordingly.
22.Write a Python program that determines whether a credit card application is approved
based on the applicant's credit scoreand income. Ask the user for their credit score and annual
income, and provide an approval status.
23.Write a Python program for vehicle registration based on the type of vehicle and
emissions. Ask the user for thevehicle type (car or truck) and emissions status (clean or high).
Provide the registration fee based on the inputs.
While loop:
1.Basic Counting: Write a while loop that counts from 1 to 10 and prints each number.
2.Create a program that asks the user to enter a number, and then use a while loop to count
down from that number to 1, printing each value.
3. Write a while loop that calculates the sum of even numbers from 1 to 100.
4.Create a simple number guessing game using a while loop. Generate a random number and
have the user guess it, giving hints like "too high" or "too low" until they guess correctly.
5.Use a while loop to calculate the factorial of a given number.
6.Write a while loop that prints all even numbers between 1 and 50.
7.Create a program that calculates the sum of the digits of a given integer using a while loop.
8.Generate a multiplication table for a given number using a while loop.
9.Write a program to find all the factors of a given number using a while loop.
10.Implement a program to reverse a given number using a while loop.
11.Create a program that prompts the user to enter a password. Keep asking until they enter
the correct password.
12.Write a program using a while loop to generate the first n terms of the Fibonacci sequence.
13.Build a program that checks if a given number is prime using a while loop.
14.Create a program that checks if a given word or phrase is a palindrome (reads the same
forwards and backwards) using a while loop.
15.Write a program to generate the first n rows of Pascal's Triangle using while loops.
Page 5 of 70
16.Create a program that converts a given integer into words (e.g., 123 -> "one hundred
twenty-three") using a while loop.
17.Write a program to reverse a given string using a while loop.
18.Implement a program to find the greatest common divisor of two numbers using a while
loop and the Euclidean algorithm.
19.Create a program that converts a binary number (entered as a string) to its decimal
equivalent using a while loop.
20. Write a program that prints all prime numbers between 1 and 100 using a while loop
21.Implement a program to calculate the result of raising a number to a given power using a
while loop, without using the built-in exponentiation operator.
22.Implement the Newton-Raphson method to calculate the square root of a number using a
while loop.
23. Write a program to explore the Collatz conjecture for a given starting number. Count how
many iterations it takes to reach 1.
24. Create a program that calculates and prints the prime factorization of a given number
using a while loop.
25.Build a program that searches for a specific word in a text using a while loop. Provide the
index of the word's first occurrence
26.Generate the Farey sequence of order n using a while loop. The Farey sequence is a list of
all simplified fractions between 0 and 1 with denominators less than or equal to n.
27. Implement matrix multiplication (matrix dot product) using nested while loops.
28.Write a program to calculate the value of the Ackermann function for given inputs (m, n)
using a while loop. The Ackermann function is a recursive function.
29.Given an unsorted array of integers, find the length of the longest consecutive elements
sequence using a while loop.
30.Implement a Sudoku solver using a while loop and backtracking algorithm to solve a
Sudoku puzzle
For Loop:
1.Print numbers from 1 to 5 using a for loop?
2.Calculate the sum of numbers from 1 to 10 using a for loop ?
3.Print even numbers from 1 to 10 using a for loop?
4.Calculate the factorial of a number using a for loop?
5.Print elements of a list using a for loop ?
6.Find the maximum value in a list using a for loop ?
Page 6 of 70
7.Print characters in a string using a for loop ?
8.Count the number of vowels in a string using a for loop ?
9.Iterate over a dictionary and print key-value pairs using a for loop ?
10.Print a pattern using nested for loops ?
11.Calculate the sum of all even numbers from 1 to 100 using a for loop ?
12.Print the first 10 Fibonacci numbers using a for loop ?
13.Find and print the common elements between two lists using a for loop ?
14.Generate a multiplication table for a given number using a for loop ?
15.Calculate the factorial of a number using a for loop with a range starting from 1 ?
16.Print the reverse of a string using a for loop ?
17.Generate a list of squares for numbers from 1 to 10 using a for loop ?
18.Count the number of words in a sentence using a for loop ?
19.Calculate the sum of digits in a number using a for loop ?
20.Generate a list of prime numbers within a given range using a for loop ?
21.Calculate the power of a number using a for loop ?
22.Reverse a list using a for loop ?
23.Find and print the largest element in a list using a for loop ?
24.Calculate the average of numbers in a list using a for loop ?
25.Print a countdown from a given number using a for loop ?
26.Generate a pattern of numbers using nested for loops ?
27.Calculate the product of elements in a list using a for loop ?
28.Find and print the position (index) of an element in a list using a for loop ?
29.Calculate the sum of all odd numbers from 1 to 100 using a for loop ?
30.Print a triangle of asterisks using a for loop ?
31.Calculate the LCM (Least Common Multiple) of two numbers using a for loop ?
32.Print a Pascal's Triangle using nested for loops ?
33.Count the number of prime numbers in a range using a for loop ?
34.Reverse words in a sentence using a for loop ?
35.Print a diamond pattern using nested for loops ?
36.Calculate the sum of the first n natural numbers using a for loop ?
Page 7 of 70
37.Print a hollow square pattern using nested for loops ?
38.Calculate the factorial of a number using a for loop with a specified step ?
39.Print a right-angled triangle pattern using a for loop ?
40.Generate a list of multiples of a number within a given range using a for loop?
Page 8 of 70
13.Write a Python program that asks the user to input a password. If the password is not at
least 8 characters long, keep asking for a valid password using a loop. Use the continue
statement to skip further processing until a valid password is provided.
14.Write a Python program to find the sum of all even numbers from 1 to 100. However, if a
multiple of 7 is encountered, skip it using the continue statement.
15.Create a Python program that generates and prints the first 10 terms of the geometric
progression (GP) with a common ratio of 2. Use a loop and the break statement to stop
generating the sequence after the 10th term.
16.Implement a Python program to count and print the number of digits in an integer. Use a
loop and the continue statement to skip non-digit characters.
17.Write a Python program to simulate a basic ATM machine. The program should repeatedly
ask the user for the amount they want to withdraw until a valid amount is entered. Use the
continue statement to retry input if the amount is not valid.
18.Create a Python program to find and print the smallest and largest numbers in a list of
integers. Use a loop, break, and continue to accomplish this.
19.Write a Python program that simulates a basic game where the player has to guess a secret
number between 1 and 100. The program should give the player up to 5 attempts, and use the
break statement to exit the game when the player either guesses the correct number or runs
out of attempts.
20.Implement a Python program that prints all the numbers from 1 to 50. However, if a
number is a multiple of both 4 and 7, skip it using the continue statement.
Pass:
1.Create a Python program that iterates over a list of integers and prints all even numbers. For
odd numbers, use the pass statement to do nothing.
2.Write a Python program that asks the user to input a list of numbers. For each number in the
list, check if it's a prime number. If it's prime, print it; if not, use the pass statement.
3.Implement a Python program that simulates a basic class structure for a geometric shape.
Create a class named Shape, and for now, use the pass statement to indicate that further
methods and attributes need to be added in the future.
4.Write a Python program that reads a text file and counts the number of lines that contain the
word "apple." For lines that don't contain the word, use the pass statement.
5.Create a Python program to check if a given number is a perfect square. If it is, print a
message; otherwise, use the pass statement.
6.Implement a Python program that iterates through a list of tasks. For each task, check if it's
completed. If it's completed, print a message; if not, use the pass statement.
7.Write a Python program to create a basic framework for a web application. Use the pass
statement for sections that require further implementation.
Page 9 of 70
8.Create a Python program that defines a class called Employee. Use the pass statement to
indicate that you need to define attributes and methods for the class later.
9.Write a Python program to iterate through a list of sentences and check if each sentence
ends with a question mark. If it does, print the sentence; otherwise, use the pass statement.
10.Implement a Python program that reads a configuration file. For each configuration item,
use the pass statement to indicate that further processing is required.
Star programs:
1.Print a simple pattern of increasing asterisks.
*
**
***
****
*****
Page 10 of 70
***
**
*
Page 11 of 70
* *
*
**
**
* *
*****
Page 12 of 70
*****
***
*
***
*****
*******
*** ***
*******
*********
*********
*********
Page 13 of 70
*******
*****
***
*
******
******
******
******
******
* *
* *
* *
**
*
**
* *
* *
* *
18. Print an arrow pattern.
*
***
*****
*******
*********
Page 14 of 70
*
*
*
* *
** **
* ** *
* * *
* *
Number Petterns:
1.Print a pattern of numbers from 1 to n in the following format:
1
22
333
4444
Page 15 of 70
4.Print a pattern of numbers with alternating rows:
1
23
456
7 8 9 10
Page 16 of 70
5
45
345
2345
12345
Page 17 of 70
1234321
12321
121
1
Page 18 of 70
11111
17.Print a pattern of numbers in a spiral order (with variable dimensions and formatting):
01 02 03 04 05
16 17 18 19 06
15 24 25 20 07
14 23 22 21 08
13 12 11 10 09
20.Print a pattern of numbers in a spiral order (with variable dimensions and formatting):
01 02 03 04 05
16 17 18 19 06
15 24 25 20 07
14 23 22 21 08
13 12 11 10 09
Page 19 of 70
Alphabet petterns:
1.Print a simple alphabet pattern:
A
BB
CCC
DDDD
EEEEE
Page 20 of 70
ABC D E
ABCD
ABC
AB
A
Page 21 of 70
AB
ABC
ABC D
ABC D E
Page 22 of 70
DDDD
EEEEE
Page 23 of 70
18.Print an hourglass pattern of alphabets:
ABC D E D C BA
BCDEDCB
CDEDC
DED
E
E
DD
C C
B B
C C
DD
E
E D C BA
D C BA
C BA
BA
A
BA
C BA
D C BA
E D C BA
Page 24 of 70
A
BB
C C
D D
E E
D D
C C
BB
A
ABCDE
B B
C C
D D
EDCBA
A M
B LN
C K O
DJ P
E Q
FI R
G H S
Page 25 of 70
A
BB
C C
D D
C C
BB
A
A
BB
C C
D D
C C
BB
A
A E
AB DE
ABC CDE
ABCD DCDE
ABCDEEDCD
Page 26 of 70
ABA
ABC BA
ABC DCBA
ABC D E D C BA
12345
ABC D E
9876F
8765G
7654H
29.Print a staircase pattern with alternating alphabets:
ABC D E
FGHI
JKL
MN
O
30.Print a heart-shaped pattern of alphabets:
A A
AAAA
A A
A
Data Structures....
List:
1.Reverse a list in Python ?
2.Remove duplicates from a list in Python ?
3.Find the maximum and minimum elements in a list ?
Page 27 of 70
4.Sort a list in ascending and descending order ?
5.Check if a list is empty in Python ?
6.Find the index of a specific element in a list ?
7.Count the occurrences of an element in a list ?
8.Merge two lists in Python ?
9.Find the sum of all elements in a list ?
10.Check if a list contains a specific element ?
11.Remove an element from a list by its value ?
12.Slice a list to get specific elements ?
13.Find the length (number of elements) of a list ?
14.Add an element to the end of a list ?
15.Iterate through a list using a for loop ?
16.Insert an element at a specific position in a list ?
17.Extend a list with elements from another iterable ?
18.Clear all elements from a list ?
19.Create a copy of a list ?
20.Check if all elements in a list satisfy a condition ?
21.Check if any elements in a list satisfy a condition ?
22.Reverse a list in-place (modify the original list) ?
23.Find the index of the first occurrence of an element from a specific position ?
24.Remove and return the last element from a list ?
25.Find the index of the last occurrence of an element in a list ?
26.Check if two lists are equal?
27.Create a list with a specified number of elements ?
28.Find the index of the maximum and minimum elements in a list ?
29.Sort a list in-place (modify the original list) ?
30.Create a list using list comprehension?
31.Find the unique elements in a list (preserve order) ?
32.Find the second largest element in a list
33.Count the number of even and odd numbers in a list:
Page 28 of 70
34.Remove elements at even indices from a list:
35.Check if a list is sorted in ascending order:
36.Find the intersection of two lists (common elements):
37.Find the union of two lists (all unique elements from both lists):
38.Find the first non-repeating element in a list:
39.Remove all occurrences of a specific element from a list:
40.Rotate a list to the right by a given number of positions:
41.Check if a list is a palindrome (reads the same forwards and backwards):
42.Find the frequency of each element in a list and store it in a dictionary:
43.Find the longest consecutive subsequence in a list:
44.Find the maximum subarray sum in a list (Kadane's Algorithm):
45.Find the intersection of multiple lists (common elements in all lists):
46.Shuffle a list randomly:
47.Find the majority element in a list (element that appears more than n/2 times, if it exists):
48.Find the kth largest element in a list:
49.Merge overlapping intervals in a list:
50.Check if a list can be divided into two equal sum subarrays:
51.Find the longest increasing subsequence in a list:
52.Find the peak element in a list (an element that is greater than its neighbors):
53.Generate all possible subsets of a list:
54.Find the longest word formed by deleting some characters of a given string
55.Find the missing number in a list containing all numbers from 1 to n except one:
56.Implement a circular queue using a list:
57.Implement a priority queue using a list:
58.Implement a stack using a list:
59.Implement a queue using two stacks:
60.Implement a linked list using a list of dictionaries:
61.Find the intersection point of two linked lists:
Page 29 of 70
Tuple:
1.Find the index of the first occurrence of a specific element in a tuple:
2.Concatenate two tuples:
3.Count the occurrences of an element in a tuple:
4.Check if an element exists in a tuple:
5.Reverse a tuple:
6.Find the maximum and minimum elements in a tuple:
7.Check if all elements in a tuple are the same:
8.Convert a tuple into a list:
9.Find the length of a tuple:
10.Sort a tuple of numbers in ascending order:
11.Find the sum of all elements in a tuple:
12.Check if a tuple is empty:
13.Find the index of the last occurrence of a specific element in a tuple:
14.Slice a tuple to extract a portion of it:
15.Check if a tuple contains only unique elements:
16.Create a tuple with a single element:
17.Convert a list into a tuple:
18.Multiply a tuple to repeat its elements:
19.Unpack a tuple into individual variables:
20.Iterate through the elements of a tuple:
21.reate a tuple with a range of numbers:
22.Find the index of the nth occurrence of a specific element in a tuple:
23.Convert a tuple of strings into a single string:
24.Check if two tuples are equal:
25.Merge two tuples into one using the + operator:
26.Create a tuple of tuples (nested tuple):
27.Find the product of all elements in a tuple of numbers:
28.Find the product of all elements in a tuple
29.Check if a tuple contains duplicate elements:
Page 30 of 70
30.Find the index of the last occurrence of a specific element in a tuple:
31.Remove an element from a tuple and create a new tuple without that element:
32.Find the difference between two tuples:
33.Count the occurrences of each element in a tuple and store the results in a dictionary:
34.Find the common elements between two tuples:
35.Create a tuple from a string:
36.Combine multiple tuples into one:
37.Convert a list of elements into a tuple:
38.Find the index of the nth occurrence of a specific element in a tuple:
39.Find the largest element in a tuple of numbers:
40.Check if two tuples are equal (have the same elements in the same order):
41.Find the sum of all elements in a tuple:
42.Create a tuple from a string:
43.Combine multiple tuples into one:
44.Convert a list of elements into a tuple:
45.Find the index of the nth occurrence of a specific element in a tuple:
46.Find the largest element in a tuple of numbers:
47.Check if two tuples are equal (have the same elements in the same order):
48.Find the index of the maximum element in a tuple:
49.Create a tuple of even numbers from an existing tuple:
50.Check if a tuple is a subset of another tuple:
51.Find the union of two tuples (unique elements from both):
52.Check if a tuple is empty without using the len() function:
53.Create a new tuple with elements reversed in order from an existing tuple:
54.Check if all elements in a tuple are unique:
55.Find the difference between two tuples (elements present in the first tuple but not in the
second):
56.Check if a tuple contains only numeric elements:
57.Find the median value of a tuple of numbers:
58.Check if a tuple is a palindrome (reads the same forwards and backwards):
59.Check if a tuple contains a specific subsequence:
Page 31 of 70
60.Find the second largest element in a tuple:
61.Find the product of the first and last elements in a tuple:
62.Find the longest consecutive subsequence in a tuple of integers:
63.Find the tuple with the maximum sum in a list of tuples:
64.Find the subarray with the maximum sum in a tuple of integers (Kadane's Algorithm for
tuples):
65.Rotate a tuple to the right by k steps:
66.Find the kth smallest and kth largest element in a tuple:
67.Find the contiguous subarray with the smallest sum in a tuple of integers (Minimum
Subarray Sum):
68.Find the longest subarray with at most k distinct elements in a tuple of integers:
Set
1.Create an empty set in Python:
2.How to add an element to a set:
3.How to remove an element from a set:
4.Check if an element exists in a set:
5.Find the length of a set:
6.Find the union of two sets:
7.Find the intersection of two sets:
8.Check if one set is a subset of another:
9.Check if two sets are disjoint:
10.Remove all elements from a set:
11.Find the maximum element in a set:
12.Find the minimum element in a set:
13.Convert a list to a set:
14.Iterate over the elements of a set:
15.Check if two sets are equal:
16.Remove an element from a set if it exists, otherwise, do nothing:
17.Create a frozen set in Python:
18.Find the difference between two sets:
19.Check if a set is empty:
Page 32 of 70
20.Remove and return an arbitrary element from a set:
21.Find the symmetric difference between two sets:
22.Update a set with the elements from another set:
23.Check if a set is a proper subset of another:
24.Find the sum of all elements in a set:
25.Find the average of elements in a set:
26.Implement set operations (union, intersection, difference):
27.Create a set with unique elements from a list:
28.Find the Cartesian product of two sets:
29.Check if two sets have at least one common element:
30.Find the second-largest element in a set:
31.Check if a set is a superset of multiple other sets:
32.Find the Jaccard similarity between two sets:
33.Find the largest subset of elements in a set that forms an arithmetic progression:
34.Compute the power set of a set:
35.Find the most common element in a set:
36.Find the intersection of N sets:
37.Find all subsets of a set with a given sum:
38.Find the smallest common element in multiple sets:
39.Find the longest consecutive sequence of elements in a set:
40.Check if two sets have the same elements but in different orders:
41.Find the largest subset of elements in a set that forms an arithmetic progression without
using built-in functions:
42.Find the Cartesian product of two sets without using built-in functions:
43.Find the Jaccard similarity between two sets without using built-in functions:
44. Implement set difference in constant time without using built-in functions.
45. Generate all unique subsets of a set without using built-in functions.
46. Implement constant-time subset testing without using built-in functions.
47. Find the longest subarray with distinct elements using a set without using built-in
functions.
48. Implement constant-time disjoint set operations without using built-in functions.
Page 33 of 70
49. Find the longest subarray with a given sum using a set without using built-in functions.
50. Implement constant-time intersection size computation without using built-in functions.
51. Find the largest subarray with equal 0s and 1s using a set without using built-in functions.
52. Implement constant-time symmetric difference size computation without using built-in
functions.
53. Find the longest subarray with equal number of 0s and 1s using a set without using built-
in functions.
54. Implement constant-time set difference size computation without using built-in functions.
55. Find the longest subarray with at most K distinct elements using a set without using built-
in functions.
56. Implement constant-time union size computation without using built-in functions.
57. Find the longest subarray with at least K distinct elements using a set without using built-
in functions.
58. Implement constant-time subset testing for multiple sets without using built-in functions.
59. Find the longest substring with at most K distinct characters using a set without using
built-in functions.
60. Implement constant-time disjoint set operations for multiple sets without using built-in
functions.
61. Find the longest substring with at least K distinct characters using a set without using
built-in functions.
62. Implement constant-time intersection size computation for multiple sets without using
built-in functions.
63. Find the longest substring without repeating characters using a set without using built-in
functions.
Dictionary:
1.Create an empty dictionary and add key-value pairs to it:
2.Accessing values associated with a specific key:
3.Adding a key-value pair or updating if the key exists:
4.Removing a specific key-value pair:
5.Dictionary comprehension (filtering):
6.Counting occurrences in a list and storing them in a dictionary:
7.Merging two dictionaries into one:
8.Finding the key with the minimum and maximum value:
Page 34 of 70
9.Sorting a dictionary by its keys in ascending order:
10.Finding the key with the longest value in a dictionary:
11.Determining the number of key-value pairs in a dictionary:
12.Updating values in a dictionary:
13.Clearing a dictionary:
14.Copying a dictionary:
15.Nested dictionaries:
16.Checking if a value exists in a dictionary:
17.Removing a key from a dictionary and getting its value:
18.Reversing key-value pairs in a dictionary:
19.Check if all keys or values meet a condition:
20.Merge two dictionaries into one (Python 3.9+):
21.Get a value with a default if the key doesn't exist:
22.Merge dictionaries using the update method:
23.Sorting a dictionary by values in ascending order:
24.Sorting a dictionary by values in descending order:
25.Checking for the existence of a key and getting its value with a default:
26.Getting a list of keys sorted by their values:
27.Getting a dictionary containing keys and their lengths (useful for strings):
28.Using a dictionary to count occurrences of elements in a list:
29.Inverting a dictionary (swapping keys and values):
30.Working with nested dictionaries (dictionary of dictionaries):
31.Merging dictionaries so that values are added together if keys exist in both dictionaries:
32.Providing a default value when accessing a key in a dictionary to handle missing keys:
33.Dictionary comprehension with conditions (creating a new dictionary with a conditional
statement):
34.Finding common keys in two dictionaries:
35.Extracting unique values from a dictionary's values:
36.Converting a dictionary to a JSON string:
37.Parsing a JSON string into a dictionary:
38.Implementing a switch-case statement using a dictionary:
Page 35 of 70
39.Counting occurrences of values in a dictionary:
40.Finding keys associated with a specific value in a dictionary:
41.Updating multiple values in a dictionary:
42.Getting a dictionary containing keys from one dictionary and values from another:
43.Combining dictionaries into a single dictionary (Python 3.9+):
44.Sorting a dictionary by values in ascending order:
45.Flattening a nested dictionary:468.Removing duplicate values from a dictionary:
46.Using a dictionary to replace values in a string:
47.Checking if two dictionaries are equal:
48.Using a dictionary to implement a simple calculator:
49.How can you remove a key-value pair from a dictionary in Python?
50.How can you safely retrieve a value from a dictionary without raising an error if the key
doesn't exist?
51.How can you create a dictionary using a list comprehension?
52.How can you merge two dictionaries in Python?
53.How can you create a nested dictionary in Python?
54.How can you find the keys with the highest values in a dictionary?
55.How can you sort a dictionary by its values in descending order?
56.How can you create a dictionary with default values for missing keys?
57.How can you create a dictionary with keys from one list and values from another list, with
a default value for missing keys?
58.How can you merge multiple dictionaries into a single dictionary?
59.How can you create a deep copy of a nested dictionary?
60.How can you create a dictionary that calculates the frequency of words in a text string?
61.How can you create a dictionary that counts the occurrence of characters in a string?
62.How can you create a dictionary that represents a sparse matrix efficiently?
63.How can you create a dictionary that represents a graph using adjacency lists?
64.How can you create a dictionary that tracks the execution time of functions?
65.How can you create a dictionary that flattens a nested dictionary into a single-level
dictionary with compound keys?
66.How can you create a dictionary that groups elements from a list by a function's result?
Page 36 of 70
67.How can you create a dictionary that memoizes the results of a recursive function?
68.How can you create a dictionary that stores and retrieves objects based on unique
identifiers?
69.How can you create a dictionary that simulates a cache with a maximum size, removing
the least recently used items when the size is exceeded?
List Comprehensions:
1.Create a list of squares from 1 to 10:
2.Filter even numbers from a list:
3.Convert characters in a string to uppercase:
4.Find common elements between two lists:
5.Extract vowels from a string:
6.Find lengths of words in a list of words:
7.Calculate the sum of squares of all even numbers from 1 to 20:
8.Generate a list of the first 10 multiples of 3:
9.Flatten a list of lists into a single list:
10.Find the intersection of two lists of numbers:
11.Filter names that start with the letter "A" from a list of names:
12.Generate a list of all prime numbers less than 50:
13.Filter strings with more than five characters from a list of strings:
14.Calculate the factorial of each number in a given list:
15.Create a list comprehension to find the squares of even numbers and cubes of odd
numbers in a given list of integers:
16.Generate a list of tuples where each tuple contains an element from two different lists:
17.Calculate the cumulative sum of a list of numbers using a list comprehension:
18.Create a list comprehension to extract the first letter of each word in a sentence:
19.Filter out duplicates from a list using a list comprehension:
20.Create a list comprehension to reverse the order of words in a sentence:
Set Comprehension:
1.Create a set comprehension that generates a set of all even numbers from 1 to 20.
2.Given a list of words, create a set comprehension that generates a set of unique words
longer than 3 characters.
3.Generate a set comprehension that extracts the vowels from a given string.
Page 37 of 70
4.Create a set comprehension that calculates the squares of numbers from 1 to 10, but only
for numbers that are divisible by 3.
5.Given two sets, A and B, create a set comprehension that generates the union of these sets.
6.Question: Create a set comprehension that generates a set of the first 10 prime numbers.
7.Given two sets, A and B, create a set comprehension that generates the symmetric
difference (elements that are in either of the sets, but not in their intersection).
8.Create a set comprehension that extracts all uppercase letters from a given string.
9.Generate a set comprehension that extracts the unique words from a list of sentences.
10.Create a set comprehension that generates a set of the squares of even numbers from 1 to
15.
11.Create a set comprehension that generates a set of all vowels in a given sentence, ignoring
case.
12.Generate a set comprehension that extracts unique words longer than 4 characters from a
list of sentences.
13.Create a set comprehension that generates a set of the first 10 multiples of 3.
14.Given a list of numbers, create a set comprehension that generates a set of squared values
if the number is positive.
15.Generate a set comprehension that extracts unique email domains from a list of email
addresses.
16.Question: Create a set comprehension that generates a set of all the distinct odd numbers
between 1 and 20.
17.Given a list of sentences, create a set comprehension that generates a set of unique words
that start with a vowel.
18.Generate a set comprehension that extracts unique positive even numbers from a given
list.
19.Create a set comprehension that generates a set of unique lowercase characters from a
given string.
20.Given a list of tuples representing points in a 2D plane, create a set comprehension that
generates a set of unique x-coordinates.
Dictionary comprehension
1.Create a dictionary comprehension that squares each number in a given list and uses the
number as the key.
2.Given two lists, one containing names and the other containing ages, create a dictionary
comprehension to map names to ages.
3.Generate a dictionary comprehension that filters out names longer than 5 characters from a
list of names.
Page 38 of 70
4.Create a dictionary comprehension to count the frequency of each character in a given
string.
5.Given a list of tuples representing words and their lengths, create a dictionary
comprehension to construct a dictionary where words are keys and lengths are values.
6.Create a dictionary comprehension that extracts all words starting with a vowel from a
given list of words.
7.Given a list of sentences, create a dictionary comprehension that counts the number of
words in each sentence.
8.Generate a dictionary comprehension that calculates the square of numbers from 1 to 10,
but only for numbers that are divisible by 3.
9.Given a list of strings, create a dictionary comprehension that maps each string to its length
and adds a key-value pair only if the length is even.
10.Create a dictionary comprehension to convert a list of integers into a dictionary where
keys are the integers themselves, and values are their squares.
11.Question: Given two lists, one containing student names and the other containing their
corresponding scores, create a dictionary comprehension to map names to scores. Only
include students with scores greater than or equal to 80.
12.Generate a dictionary comprehension that extracts unique first letters from a list of words
and counts their occurrences.
13.Create a dictionary comprehension that extracts all words longer than 4 characters from a
given list of sentences and uses the words as keys with their lengths as values.
14.Given a list of email addresses, create a dictionary comprehension that maps the username
(before '@') to the domain.
15.Create a dictionary comprehension that extracts all uppercase letters from a given string
and counts their occurrences.
16.Question: Given a list of numbers, create a dictionary comprehension to group the
numbers by whether they are even or odd.
17.Generate a dictionary comprehension that combines two lists into a dictionary where
elements from one list are keys and elements from the other list are values.
18.Create a dictionary comprehension to extract all words from a list of sentences and count
their occurrences in the entire text.
19.Given a list of strings, create a dictionary comprehension that maps each string to its
length and adds a key-value pair only if the length is odd.
20.Generate a dictionary comprehension to calculate the factorial of numbers from 1 to 5.
Page 39 of 70
Shuffling
1.Given a list of numbers, shuffle its elements.
2.Create a program that simulates picking a random card from a deck.
3.Shuffle a deck of cards and deal 5 cards.
4.Given a sentence, shuffle its words.
5.Given a list of numbers, shuffle the even and odd numbers separately and then merge them.
6.Given two lists, shuffle them together such that one element from the first list is followed
by one from the second, and so on.
7.Given a list of numbers, shuffle them such that no two even numbers or two odd numbers
come together.
8.Given a list of names, create random pairs.
9.Given a string, shuffle its characters but ensure vowels remain in the same position.
10.Shuffle a deck of cards and deal n hands of m cards each.
11.Given a list of numbers, shuffle it such that no number is next to its original neighbors.
12.Given a list, shuffle its elements such that elements which are the same are at least 2
positions away from each other.
13.Given two decks of cards, shuffle them together, ensuring that no two cards from the same
deck come together.
14.Given a 2D matrix, shuffle its rows but maintain the relative order of elements within each
row.
15.Given a paragraph (multiple sentences), shuffle the sentences.
SWAPPING
1.Given two numbers, swap their values without using a third variable.
2.Given two strings, swap their values.
3.Given a list, swap its first and last elements.
4.Given a string, swap the characters at positions i and j
5.Given a list, swap elements at even indices with elements at odd indices.
6.Given a list, swap every pair of elements and then reverse the entire list.
7.Given a matrix (2D list), swap the first and last elements of each row.
8.Given a list of integers, swap each negative number with the nearest preceding positive
number.
9.Given two lists of equal length, swap the i-th element of the first list with the i-th element
of the second list.
Page 40 of 70
10.Given two lists, swap their middle elements. If a list has an even number of elements,
consider the latter middle.
11.Given a list, repeatedly swap the largest number in the list with its right neighbor until it
reaches the end of the list.
12.Given a list, swap every element with its mirrored position. For instance, the first element
is swapped with the last, the second with the second last, and so on.
13.Given a list of integers, for each element, swap it with the nearest element of the same
value. If there's no other element with the same value, leave it in its place.
14.Given two lists of the same length, swap their elements in an alternating pattern: one from
the first list, one from the second, and so on.
15.Check if it's possible to make a string a palindrome by swapping exactly two characters.
SORTING
1.Given a list of numbers, sort them in ascending order.
2.Given a list of strings, sort them alphabetically.
3.Given a list of strings, sort them by their length.
4.Given a list of numbers, sort them in descending order.
5.Given a list of tuples where each tuple contains two elements, sort the list based on the
second element of each tuple.
6.Given a list of words, sort them based on their last character.
7.Given a list of numbers, sort them based on their frequency in the list. If two numbers have
the same frequency, sort them in ascending order.
8.Given a matrix (2D list), sort its rows based on the sum of elements in each row.
9.Given a list of numbers and a reference number, sort the list based on the absolute
difference between each number and the reference number.
10.Given a list of integers and strings, sort them such that all strings are on the left and all
integers are on the right.
11.Given a list of words, sort them based on the count of vowels in each word. If two words
have the same vowel count, maintain their relative order.
12.Given a list of numbers, sort the list such that all even numbers are on the left and all odd
numbers are on the right, with both sections sorted in ascending order.
13.Given a list of strings and a custom alphabet order, sort the strings based on this custom
order.
14.Given a matrix (2D list), sort its columns based on the sum of elements in each column.
15.Given a list of numbers, sort them such that all prime numbers are on the left and non-
prime numbers on the right, with both sections sorted in ascending order.
Page 41 of 70
Strings:
Questions:
1. Reverse a string
2.Count vowels
3. Capitalize First Letter of Words
4.Check palindrome
5.Count Occurrences of Substring
6.Length of string
7.Convert to Uppercase
8.Convert to Lowercase
9.Concatenate Strings
10.Check if Character Exists
11.Print First and Last Character
12.Add an Exclamation to a String
13. String Repetition
14.String Spaces
15. Replace a Character
16.Display Your Name
17.Simple Greeting
18.Count the number of times the letter 'e' appears in a given string.
19. Simple String Concatenation
20. Is the String Empty?
21.Write a program to remove all vowels from a given string.
22.Count Words
23.Check if String is a Palindrome (ignoring spaces)
24.Given a string, display it in a pyramid format.
25.Encode String Write a program that encodes a string by replacing each letter with the next
letter (i.e., replace 'a' with 'b', 'b' with 'c', ..., 'z' with 'a').
26. Find the Longest Word
Page 42 of 70
27.Determine if two given strings are anagrams (i.e., they contain the same characters in any
order).
28.Count the number of consonants in a given string.
29.Extract all the numbers from a given string and display them.
30.Find All Occurrences of Substring
31.Implement a basic string compression using counts of repeated characters. For example,
the string "aabcccccaaa" would become "a2b1c5a3". If the compressed string is not smaller
than the original string, return the original string.
32.Rotate a string to the right by a given number of positions
33.Count the occurrence of each character in a string.
34.Given two strings, interleave their characters starting with the first string. If one string is
longer than the other, append the remaining characters of the longer string at the end
35.Check if a string is a subsequence of another string. A string s1 is a subsequence of s2 if
the characters of s1 appear in the same order in s2, though not necessarily consecutively.
36.Check if a given string can be constructed by taking a substring and repeating it
37.First Non-Repeating Character Given a string, find the first non-repeating character in it.
38.Check if one string is a permutation of another
39.Determine if the input string has valid parentheses. For example, "()" and "()[]{}" are
valid, but "(]" and "([)]" are not.
40.Given a string, reverse the order of its words
41.Check if a string s2 is a rotation of another string s1.
42.Given a string, determine if it is a palindrome by considering only alphanumeric
characters and ignoring cases.
43.Intersperse two strings. If one string runs out before the other, append the rest of the
longer string to the result.
44.Find the first character in a string that repeats
45.Given a string s consisting of some words separated by spaces, return the length of the last
word in the string. If the last word does not exist,
return 0. A word is defined as a sequence of non-space characters.
46.Given a string, find its lexicographical rank among its permutations.
47.Remove all adjacent duplicate characters from a string. Continue removing until no more
adjacent duplicates are found.
48.Given two strings s and p, find all the start indices of p's anagrams in s.
49.Given a list of strings, find the longest common prefix among them.
Page 43 of 70
50.Count the number of substrings in a binary string that contains the same number of 0s and
1s without any overlap.
51.Implement a function that converts a string to an integer. The function should handle
positive/negative sign and ignore leading/trailing whitespaces.
Do not use the built-in int() function.
52.Given a Roman numeral, convert it to its integer value.
53.Given an integer n, generate the nth term of the "count and say" sequence.
54.Check if a given string can become a palindrome by deleting at most one character from it.
55.Given an array of strings, group anagrams together
56.Given two strings, check if they are one edit distance apart, i.e., they can become equal by
adding, deleting, or replacing exactly one character.
57.Given two non-negative integers num1 and num2 represented as strings, return the product
of num1 and num2, also represented as a string.
58.Write a function that converts a string to a ZigZag pattern for a given number of rows.
59.Given a string s, you can convert it to a palindrome by adding characters in front of it.
Find and return the shortest palindrome you can find by performing this transformation
60.Given a non-empty string containing only digits, determine the total number of ways to
decode it into alphabets (e.g., '1' can be decoded to 'A', '26' can be decoded to 'Z').
61.Compress a string such that 'AA' becomes 'A2' but single letters should remain unchanged.
Return the shortest compressed string possible.
62.Display a String
63.Access a Character in a String
String methods:
1. capitalize()
Converts the first character of a string to uppercase.
2. casefold()
Converts string to lowercase, it's more aggressive than lower() and can modify strings to be
more suitable for caseless comparisons.
3. center()
Returns a centered string.
4. count()
Counts the occurrences of a substring in string.
5. encode()
Page 44 of 70
Returns an encoded version of the string.
6. endswith()
Checks if the string ends with the specified suffix.
7. expandtabs()
Replaces tab characters with spaces.
8. find()
Finds a substring in a string. Returns -1 if not found.
9. format()
Formats the string.
10. index()
Like find(), but raises an exception if not found.
11. isalnum()
Checks if the string has only alphanumeric characters.
12. isalpha()
Checks if the string has only alphabetic characters.
13. isdecimal()
Checks if the string has only decimal characters.
14. isdigit()
Checks if the string has only digits.
15. isidentifier()
Checks if the string is a valid identifier.
16. islower()
Checks if all the letters in the text are in lowercase.
17. isnumeric()
Checks if the string has only numeric characters.
18. isprintable()
Checks if the string is printable.
19. isspace()
Checks if the string has only whitespace characters.
20. istitle()
Page 45 of 70
Checks if the string is in title case.
21. isupper()
Checks if all the letters in the text are in uppercase.
22. join()
Concatenates a list of strings.
23. ljust()
Returns a left-justified version of the string.
24. lower()
Converts the string to lowercase.
25. lstrip()
Removes leading whitespace.
26. partition()
Divides a string based on a separator.
27. replace()
Replaces a substring with another.
28. rfind()
Finds a substring in a string, starting from the right. Returns -1 if not found.
29. rindex()
Like rfind(), but raises an exception if not found.
30. rjust()
Returns a right-justified version of the string.
31. rpartition()
Like partition(), but starts from the right.
32. rsplit()
Splits a string into a list, starting from the right.
33. rstrip()
Removes trailing whitespace.
34. split()
Splits a string into a list.
35. splitlines()
Page 46 of 70
Splits a string by line breaks.
36. startswith()
Checks if the string starts with a specific substring.
37. strip()
Removes both leading and trailing whitespace.
38. swapcase()
Swaps cases, lowercase becomes uppercase and vice versa.
39. title()
Converts the first character of each word to uppercase.
40. upper()
Converts a string into uppercase.
41. zfill()
Fills the string with a specified number of 0 values at the beginning.
42. removeprefix() and removesuffix() (Python 3.9+)
Removes a specified prefix or suffix from a string.
43. maketrans() and translate()
These two methods are used together for character mapping. The maketrans() method returns
a translation table. The translate() method returns a string where some specified characters
are replaced with the character described in a dictionary, or in a mapping table.
44. isascii() (Python 3.7+)
Checks if all the characters in the text are ascii characters.
45. isprintable()
Checks if all the characters in the text are printable:
46. rstrip()
Removes trailing characters (based on the string argument passed).
47. lstrip()
Removes leading characters.
48. casefold()
Returns a string where all the characters are lower case.
49. format_map()
Formats specified values in a string:
Page 47 of 70
50. join()
Takes all items in an iterable and joins them into one string.
51. ljust()
Returns a left justified version of the string.
52. rjust()
Returns a right justified version of the string.
53. strip()
Removes any leading (spaces at the beginning) and trailing (spaces at the end) characters.
54. swapcase()
Swaps cases, lowercase becomes uppercase and vice versa.
Slicing:
1.Given a string, slice it to extract the first 3 characters.
2. Reversing a List
3. Slicing a Tuple
4. Modify a List Using Slicing
5. Extract Even-Indexed Characters from a String
6. Slicing a List of Lists
7. Slicing a String in Reverse
8. Slicing a List of Numbers to Get Even Numbers
9. Slicing and Modifying a String
10. Slicing with a Step of 3
11. Combining Slicing and String Methods
12. Slicing a List of Strings
13. Extracting Odd-Indexed Elements from a List
14. Reversing a List of Strings
15. Slicing with Negative Indices
16. Slicing and Duplicating a List
17. Slicing Nested Lists
18. Slicing a List in Chunks
19. Slicing a String with a Step Value
Page 48 of 70
20. Slicing to Create a New String
21. Slicing and Summing a List
22. Slicing and Concatenating Lists
23. Slicing a List to Remove Duplicates
24. Slicing a String and Reversing Words
25. Slicing and Flattening Nested Lists
26. Slicing and Finding the Maximum Value
27. Slicing and Counting Occurrences
28. Slicing and Checking Palindromes
29. Slicing and Merging Dictionaries
30. Slicing and Calculating Averages
----------------------------------------------------------------------------------------------------------------
Functions
----------------------------------------------------------------------------------------------------------------
Example 1 A simple function without arguments and return statement
Example 2: A function with parameters
Example 3: A function with default parameter
Example 4: A function with docstring
Page 49 of 70
Anonymous Functions (Lambda Functions):
Example 1 - Lambda function to square a number:
Example 2 - Lambda function to add two numbers:
Example 3 - Lambda function to find the maximum of two numbers:**
Example 4 - Lambda function to check if a number is even:
Example 5 - Lambda function to extract the last character from a string:
Example 6 - Lambda function to calculate the square root of a number using the math
module:
Example 7 - Lambda function to sort a list of tuples based on the second element:
Example 8 - Lambda function to filter even numbers from a list:
Example 9 - Lambda function with conditional expression to categorize ages:
Example 10 - Lambda function to calculate the factorial of a number using recursion:
Recursion
Example 1 Factorial Calculation:
Example 2 Fibonacci Sequence:
Example 3 Sum of Digits:
Example 4 Exponentiation:
Example 5 Binary Search:
Page 50 of 70
Example 6 Palindrome Check:
Example 7 GCD (Greatest Common Divisor) Calculation:
Function Arguments
Default arguments
Example 1: Basic Function with Default Argument
Example 2: Function with Multiple Default Arguments
Example 3: Default Argument with Lists
Example 4: Default Argument with None
Keyword arguments
Example 1: Basic Keyword Argument Usage
Example 2: Keyword Arguments with Default Values
Example 3: Keyword Arguments with Input Validation
Example 4: Keyword Arguments for File I/O
Example 5: Keyword Arguments for Function with Multiple Parameters
Page 51 of 70
# Example usage
numbers = [1, 2, 3, 4, 5]
total = sum_values(*numbers)
print(f"Sum of {numbers} is {total}")
Concatenate Strings:
# Example usage
words = ["Hello", ", ", "World", "!"]
sentence = concatenate_strings(*words)
print(sentence)
Find Maximum Number:
# Example usage
numbers = [12, 45, 67, 23, 56]
max_value = find_max(*numbers)
print(f"The maximum number in {numbers} is {max_value}")
Calculate Average:
# Example usage
grades = [85, 92, 78, 90, 88]
average_grade = calculate_average(*grades)
print(f"The average grade is: {average_grade:.2f}")
Page 52 of 70
Variable-length keyword argument dictionaries (**kwargs)
def print_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
Page 53 of 70
Built-in higher-order functions (e.g., `map`, `filter`, `reduce`)
Square all elements in a list:
Convert a list of strings to uppercase:
Filter Function:
Example 1 - Filter even numbers from a list:
Example 2 - Filter names with more than 5 characters from a list:
Decorators
Example 1: Basic Decorator
Example 2: Decorator with Arguments
Example 3: Timing Decorator
Example 4: Logging Decorator
Example 5: Memoization Decorator (Caching)
Closures
Simple Nested Function:
Returning a Nested Function:
Using Parameters in Nested Function:
Page 54 of 70
Accessing variables in outer function scopes
Accessing Outer Variable in Nested Function:
Modifying Outer Variable in Nested Function:
Closure properties
Creating a Closure:
Closure with Mutable State:
Call stack
Recursive Function Call Stack:
Call Stack Overflow (Infinite Recursion):
Generator Functions
- `yield` statement
Simple Generator:
Page 55 of 70
-------------------------
10. **Built-in Functions:**
------------------------------------
- Python's standard library functions
File I/O with open():
_______________________________________________
Mathematical Operations with math module:
_______________________________________________
Date and Time with datetime module:
_______________________________________________
Working with JSON using json module:
_______________________________________________
Regular Expressions with re module:
----------------------------------------------------------------------------------------------
- Commonly used built-in functions (e.g., `len()`, `range()`, `zip()`)
_______________________________________________
range() - Generate a Range of Numbers:
_______________________________________________
zip() - Combine Lists:
_______________________________________________
sum() - Calculate Sum:
______________________________________________
input() - User Input:
--------------------------------------
11. **Custom Function Libraries:**
------------------------------------
- Creating and using custom function libraries/modules
_________________________________
Math Operations Module:
_______________________________________________
Page 56 of 70
Data Processing Module:
_______________________________________________
File Handling Module:
-------------------------------------------------------_
- Packaging and distributing functions
----------------------------------------------------------------------------------------------------------------
Page 57 of 70
6 car class:
7.Library Book Class:
8. Create a class Rectangle that calculates the area and perimeter of a rectangle.
9. Create a class Person that stores and displays information about a person's name and age.
10.Create a class Calculator that performs basic arithmetic operations:addition, subtraction,
multiplication, and division.
11.Create a class Circle that calculates the area and circumference of a circle.
12. Create a class Student that represents a student's information, including name,roll number,
and marks in three subjects. Calculate the average marks and display the student's details.
13.Create a class BankAccount that represents a simple bank account. Implement methods for
deposit, withdrawal, and checking the account balance.
14. Create a class Car that simulates a car with attributes like make, model, and current speed.
Implement methods to accelerate and brake the car.
15.Create a class Book that represents a book with attributes like title, author, and publication
year. Implement a method to display book details.
16.Create a class Employee to represent employee information, including name, employee
ID, and salary. Implement a method to give a salary raise and display employee details.
17.Create a class Bank that represents a bank with attributes like name and location.
Implement methods to add and display account holders' names.
18.Create a class TemperatureConverter that converts temperatures between Celsius and
Fahrenheit. Implement methods for conversion in both directions.
19.Create a class Vector that represents a 2D vector with attributes x and y. Implement
methods to calculate the magnitude and display the vector.
20.Create a class Shop that represents an online shop. Implement methods for adding
products to the shop and displaying the list of available products.
Inheritance
1.Create a base class Animal that has a method sound. Extend this class with subclasses Dog
and Cat where both provide their specific implementations for the sound they make
2.Develop a base class Vehicle with a method type_of_vehicle. Extend this class with
subclasses Bike and Car, and provide specific types for each vehicle.
3.Design a base class Fruit with an attribute taste. Extend this class with subclasses Apple and
Orange, setting their specific taste in their constructors.
Page 58 of 70
4.Create a base class Bird that has a method fly. Extend this class with subclasses Sparrow
and Ostrich. While the Sparrow can fly, the Ostrich cannot.
5.Develop a base class Shape with a method area. Extend this class with subclasses Square
and Circle. The subclasses should calculate their specific areas based on their attributes.
6.Design a base class Person with attributes name and age. Extend this class with subclasses
Student and Teacher. The Student class should have an additional attribute grade, and the
Teacher class should have an attribute subject.
7.Design a class hierarchy for a university system. Begin with a base class UniversityMember
with attributes name and id_number. Extend this class with subclasses Student and Professor.
The Student class should have additional attributes like major and year, while the Professor
class should have department and publications.
8.Create a banking system. Start with a base class Account with methods deposit, withdraw,
and balance. Extend this class with subclasses SavingsAccount and CheckingAccount.
SavingsAccount should have an added interest rate, while CheckingAccount may have an
overdraft limit.
9.Develop a system to manage products in a store. Design a base class Product with attributes
name and price. Extend this class with DiscountedProduct, which should apply a discount
percentage to the product's price.
10.Design a class hierarchy for a transportation system. Create a base class Vehicle with
attributes make and model, and methods start and stop. Extend this class with subclasses Car
and Boat. The Car class should have an additional method honk, while the Boat class should
have a method anchor.
11.Develop a system to manage different types of employees in a company. Start with a base
class Employee with attributes name and salary, and a method display_salary. Extend this
with subclasses Manager and Intern. A Manager has an additional bonus to their salary, while
an Intern has a stipend instead of a regular salary.
12.Design a library system with a base class Book that has attributes title and author. Extend
this class with subclasses Fiction and NonFiction. The Fiction class should have an additional
attribute genre, and the NonFiction class should have an attribute subject.
13.Question:
Design a comprehensive school system. Create a base class Person with attributes name and
id_number. Extend this class with subclasses Student, Teacher, and Administrator. Each
subclass should have:
Student: attributes for grades (a dictionary with subjects and marks) and methods to
calculate average grade.
Teacher: attributes for subject and students_taught (a list of students) and methods to
assign grades.
Administrator: methods to add or remove students and teachers.
Page 59 of 70
14.Design a multi-layered game system. Begin with a base class Character with attributes
name, health, and methods attack and defend. Extend this class with subclasses Warrior and
Mage. Each subclass should have unique attributes:
Warrior: attributes for strength and a method to power_strike.
Mage: attributes for mana and a method to cast_spell.
15.Design an e-commerce system with product ratings and reviews. Start with a class Product
with attributes name and price. Extend this class with RatedProduct, which has attributes to
keep track of average rating and reviews.
16.Design a class hierarchy for a zoo. Create a base class Animal with attributes name, age,
and methods sound and eat. Extend this class with two subclasses Mammal and Bird. Further
extend Mammal with Lion and Dolphin and extend Bird with Eagle and Penguin. Each
subclass should provide its specific implementation for the sound it makes.
17.Develop a system to manage a computer network. Begin with a base class Device with
attributes ip_address and methods connect and shutdown. Extend this with subclasses Server,
Client, and Router. The Server should have methods to serve_data, the Client to request_data,
and the Router to route_data.
18.Design a digital library system. Start with a base class Content having attributes title and
size. Extend this class with subclasses Book and Video. The Book class should have
additional attributes like author and number_of_pages, while the Video class should have
duration and director.
Abstraction
1.Create a class Smartphone that abstracts the idea of a smartphone. It should have methods
to call, text, and browse but will not have the inner workings of these methods defined.
Extend this class with a specific smartphone brand (e.g., iPhone) that implements the
methods.
2.Design an abstract class Vehicle that represents general vehicles. It should have methods to
start_engine, stop_engine, and drive. Then, implement a class Car that inherits from Vehicle
and provides a concrete implementation for these methods.
3.Design an abstract class Appliance that represents general household appliances. This class
should have methods turn_on and turn_off. Extend this class with two specific appliances:
Refrigerator and Fan, implementing the methods.
4.Design an abstract class Instrument that represents musical instruments. It should have a
method play. Implement two specific instruments: Guitar and Drum, providing specific
sounds when played.
5.Create an abstract class Document that represents written documents. It should have
methods read and write. Implement two specific types of documents: Letter and Report, and
give specific implementations for reading and writing.
Page 60 of 70
6.Design an abstract class Payment that outlines the structure for making payments. It should
have methods authorize, pay, and refund. Now, implement two specific payment methods:
CreditCard and PayPal, each having its specific way of handling the payment operations.
7.Design an abstract class Database that provides a blueprint for database operations. It
should have methods connect, query, and close. Implement two specific databases: MySQL
and MongoDB, each offering its way of handling these operations.
8.Develop an abstract class Shape that represents geometric shapes. It should have methods
area and perimeter. Implement two specific shapes: Rectangle and Circle, providing
calculations for their area and perimeter.
9.Design an abstract class FileHandler that outlines the blueprint for handling files. It should
have methods open, read, write, and close. Implement specific handlers for different types of
files: TextFile and BinaryFile.
10.Design an abstract class DatabaseQuery to outline the blueprint for making database
queries. It should have methods connect, select, update, and disconnect. Extend this class
with SQLDatabase and NoSQLDatabase which provides different ways of executing these
queries
11.Develop an abstract class NotificationService representing a service to send notifications.
It should have methods authenticate, send and logout. Implement two specific services:
EmailService and SMSService, which use different protocols for sending notifications.
12.Develop an abstract class CloudProvider representing a cloud computing service. This
class should define abstract methods for create_instance, terminate_instance, store_data, and
retrieve_data. Implement two cloud providers: AWS and Azure, simulating the provision of
resources and storage operations.
13.Design an abstract class ECommercePlatform which defines a blueprint for an e-
commerce system. The class should have abstract methods for list_product, add_to_cart,
checkout, and make_payment. Implement two subclasses Shopify and Magento, providing
specific implementations for these methods.
14.Develop an abstract class SocialMediaPlatform that outlines functionalities for a social
media service. The class should have abstract methods for post_content, comment, like, and
share. Implement subclasses for two hypothetical platforms: Facegram and Twitbook, each
with distinct ways of handling these operations.
15.Design an abstract class GamingPlatform that simulates the workings of a gaming console.
It should have methods for load_game, play, save_game, and shutdown. Now, simulate two
platforms: PlayBox and GameStation, each having unique ways of executing the operations.
16.Develop an abstract class StreamingService representing online media streaming. The
class should have methods for login, search_content, stream, and logout. Now, create two
specific streaming platforms: Netflex and PrimeWatch to simulate their unique behaviors.
17.Develop an abstract class ArtificialIntelligence that outlines foundational operations for an
AI system. The class should have methods for train, predict, evaluate, and update_model.
Implement two specific AI frameworks: TensorFlowModel and PyTorchModel, each
simulating their distinct way of handling these operations.
Page 61 of 70
18.Design an abstract class DatabaseMigration to simulate the migration of databases. The
class should have methods for backup, transform, migrate, and validate. Implement two
specific database migration tools: SQLMigrator and NoSQLMigrator to provide distinct
methods for these operations.
19.Design an abstract class OperatingSystem which simulates the basic operations of an OS.
The class should have abstract methods for boot_up, shut_down, install_application, and
uninstall_application. Create two subclasses WindowsOS and LinuxOS that implement the
behavior for these operations.
20.Create an abstract class MusicPlayer that simulates basic operations for playing audio. The
class should have methods for play_song, pause, next_track, and previous_track. Develop
two specific audio players: SpotifyPlayer and AppleMusicPlayer that have distinct behaviors
for these operations.
21.Construct an abstract class VehicleControlSystem simulating a vehicle's control system.
The class should have methods for start_engine, stop_engine, turn_on_headlights, and
play_radio. Create two subclasses CarControlSystem and MotorbikeControlSystem to
represent their specific control behaviors.
Polymorphism
1.Define two classes, Rectangle and Circle. Both classes should have a method area that
calculates and returns their respective areas. Create objects of these classes and add them to a
list. Iterate over this list to print the area for each shape.
2.Create classes Car and Bike. Both should have a method num_of_wheels that returns the
number of wheels they have. Instantiate objects from these classes, add them to a list, and
then iterate over this list to print the number of wheels each vehicle has.
3.Design classes Apple and Orange. Both classes should have a method color that returns
their respective colors. Create instances of these classes, add them to a list, and then loop
over this list to display the color of each fruit.
4.Design classes Lion and Elephant. Both classes should have a method type which returns
whether they are herbivores or carnivores. Instantiate objects of these classes, add them to a
list, and then loop over this list to display the type of each animal.
5.Create classes named Pen and Pencil. Both should have a method is_erasable which returns
if their marks can be erased or not. Instantiate objects from these classes, place them in a list,
and then loop over this list to indicate whether each item's marks are erasable.
6.Design classes Sunflower and Rose. Both should have a method smell that returns their
characteristic smell. Create instances of these classes, add them to a list, and then loop over
this list to display the smell of each flower.
7.Design a system with a base class Vehicle that has a method capacity. Extend this class into
two subclasses: Bus and Car. While Bus can carry multiple passengers, Car is meant for
fewer passengers. Instantiate objects of these classes, add them to a list, and loop over this list
to display the capacity of each vehicle.
Page 62 of 70
8.Construct a class hierarchy for animals with a base class Animal. This class should have a
method diet which returns the general diet of the animal. Extend this with two subclasses:
Carnivore and Herbivore. Further, extend Carnivore with a class Tiger and Herbivore with a
class Cow. Instantiate objects and display their diets.
9.Design a base class Shape with a method perimeter that returns the perimeter of the shape.
Extend this class with subclasses: Triangle and Rectangle. The perimeter calculation varies
for each shape. Instantiate objects from these subclasses, place them in a list, and then loop
over this list to display the perimeter of each shape.
10.Design a system where you have a base class Instrument that has a method sound. Extend
this class with three subclasses: Guitar, Piano, and Drums. Each subclass should provide its
own implementation for the sound method. Instantiate objects of these subclasses, add them
to a list, and loop over this list to play the sound of each instrument.
11.Create a class hierarchy for a library system. Start with a base class Book that has a
method genre. Extend this with two subclasses: Fiction and NonFiction. Further extend
Fiction with classes SciFi and Romance, and NonFiction with History and Biography.
Instantiate objects and determine their genre.
12.Design a class hierarchy for electronic devices. Create a base class Device with a method
purpose. Extend this with ComputingDevice and CommunicationDevice. Further extend
ComputingDevice with Laptop and Desktop, and CommunicationDevice with MobilePhone
and Landline. Instantiate these and display their purposes.
13.Design a simple simulation of a zoo with different animal types and behaviors. Start with
a base class Animal that has methods sound, eat, and move. Extend this with classes Bird,
Mammal, and Fish. Each of these subclasses should override the methods in unique ways.
Further, extend Bird with Eagle and Penguin, Mammal with Lion and Kangaroo, and Fish
with Shark and Clownfish. Instantiate these subclasses and demonstrate their behaviors.
14.Design a system to manage different types of documents. Start with a base class
Document that has methods content_type and print_content. Extend this with TextDocument,
PDFDocument, and ImageDocument. Each subclass should handle its unique content type
and print method. Instantiate these classes and demonstrate their content handling and
printing capabilities.
15.Create a simulation of geometric transformations on shapes. Start with a base class Shape
with methods translate and scale. Extend this with Circle and Rectangle. Both subclasses
should have their own methods to modify the position or dimensions, influenced by the base
class's transformations.
16.Design a system to simulate different types of printers in an office setting. Start with a
base class Printer with methods connect and print_document. Extend this class with
subclasses: LaserPrinter, InkjetPrinter, and DotMatrixPrinter. Each subclass should
demonstrate unique behaviors while connecting and printing. Instantiate these classes and
demonstrate the printer operations.
Page 63 of 70
17.Design a simulation where different storage devices can read and write data. Begin with a
base class StorageDevice having methods read and write. Extend this with classes:
HardDrive, SSD, and USBStick. Each subclass should provide specific reading and writing
speeds. Instantiate and demonstrate data operations on these storage devices.
18.Design a class hierarchy for different payment methods in an e-commerce system. Begin
with a base class Payment with methods authorize and charge. Extend this with CreditCard,
DebitCard, and PayPal. Each subclass should implement authorization and charging uniquely.
Instantiate these classes and demonstrate a payment flow.
19.Create a simulation of a multimedia system. Begin with a base class Media with methods
play and stop. Extend this with subclasses AudioFile, VideoFile, and ImageFile. Each
subclass should simulate the playing and stopping of its content type in unique ways.
Instantiate these classes and demonstrate their behaviors.
20.Design a logging system. Start with a base class Logger having methods info, error, and
warning. Extend this with ConsoleLogger, FileLogger, and NetworkLogger. Each subclass
should have its own way of logging messages to its medium. Instantiate and demonstrate
logging actions using these classes.
21.Design a database access layer. Create a base class Database with methods connect and
query. Extend this class with SQLDatabase, NoSQLDatabase, and InMemoryDatabase. Each
subclass should showcase unique connection and query behaviors. Instantiate these classes
and demonstrate their operations.
Method-Overriding
1.Design a base class Shape with a method area that returns 0. Create two subclasses, Circle
and Square, and override the area method to return the appropriate area for each shape.
2.Design a base class Animal with a method sound that returns "Animal makes a sound".
Develop two subclasses, Dog and Cat, and override the sound method to produce the sound
each animal generates.
3.Construct a base class Vehicle with a method description that returns "This is a vehicle".
Generate two subclasses, Car and Bike, and override the description method to return more
specific descriptions for each type of vehicle.
4.Design a base class Bird with a method fly that returns "A bird can fly". Create two
subclasses, Ostrich and Penguin, and override the fly method for these birds since they cannot
fly.
5.Create a base class Fruit with a method taste that returns "A fruit has a taste". Develop two
subclasses, Mango and Lemon, and override the taste method to return the specific taste for
each fruit.
6.Design a base class Device with a method power_on that returns "Device is powering on".
Construct two subclasses, Laptop and Smartphone, and override the power_on method to
give a customized power-on message for each device.
Page 64 of 70
7.Create a class BankAccount with methods deposit, withdraw, and get_balance. The
get_balance method should simply return the balance. Now, derive a subclass
InterestAccount that overrides the get_balance method to include interest on the balance.
8.Design a class Printer that has a method print_page which returns "Printing page...". Create
a subclass ColorPrinter that overrides the print_page method to specify that it's printing in
color.
9.Build a class EBook with a method read that returns "Reading ebook...". Derive a subclass
AudioBook from EBook that overrides the read method to return a message indicating it's
playing the audiobook.
10.Design a class Database with methods connect and disconnect which respectively return
"Connecting to database..." and "Disconnecting from database...". Now, create a subclass
SecureDatabase that overrides the connect method to include a security handshake during
connection.
11.Build a class OnlineGame with methods start_game and end_game. The start_game
method should return "Starting online game..." and end_game should return "Ending online
game...". Derive a subclass BattleRoyaleGame that overrides the start_game method to
specify that players are joining a battle royale match.
12.Establish a class Vehicle with a method fuel_up that returns "Fueling up vehicle...". Create
a subclass ElectricCar that overrides the fuel_up method to indicate that the vehicle is
charging its battery.
13.Design a class Server with methods start, stop, and restart. Now, create a subclass
LoadBalancedServer that overrides the start and restart methods. The overridden methods
should initiate a health check of connected nodes before starting or restarting.
14.Develop a class Document with a method save that saves the document. Now, derive a
subclass EncryptedDocument that overrides the save method. The overridden method should
first encrypt the content before saving.
15.Design a class ECommerceSite with methods add_to_cart, remove_from_cart, and
checkout. Now, derive a subclass PremiumECommerceSite which overrides the checkout
method. In the overridden method, apply a discount for premium users before proceeding to
checkout.
16.Design a class API with methods request, response, and error. The request method
simulates sending a request, the response returns a simple response, and the error handles
errors. Now, extend this with a LoggedAPI subclass that overrides these methods to log every
action performed.
17.Construct a class Graphics with methods draw_circle and draw_square. Both methods
simply return messages indicating that a circle or square is drawn. Extend this with a subclass
3DGraphics that overrides these methods to draw 3D circles and squares.
18.Create a class DatabaseQuery with a method execute that simply returns "Query
executed.". Extend this with a subclass VerifiedQuery that overrides the execute method to
first validate the query before executing.
Page 65 of 70
19.Construct a class FileSystem with methods read_file and write_file simulating basic file
operations. Now, derive a subclass EncryptedFileSystem that overrides these methods to
perform encryption on writing to a file and decryption on reading from it.
20.Design a class WebPage with methods load_page and display_content. The methods
simulate the loading and display of a web page. Extend this with a subclass MobileWebPage
that overrides these methods to optimize for mobile displays.
21.Establish a class Calculator with a method calculate that takes in an expression and returns
the result. Extend this with a subclass SafeCalculator that overrides the calculate method to
first check if the expression is safe and doesn't contain any unsafe operations.
OPERATOR OVERLOADING
1.Design a class Point representing a 2D point with x and y coordinates. Overload the +
operator to allow addition of two points.
2.Construct a class Length representing a distance in meters. Overload the < and > operators
to compare two lengths.
3.Develop a class StringRepeater with a single attribute string. Overload the * operator to
repeat the string a specified number of times.
4.Design a class Fraction that represents a simple fraction with a numerator and a
denominator. Overload the == operator to allow comparison of two fractions.
5.Construct a class Box representing a box with a certain weight. Overload the += operator to
allow combining (adding) the weight of two boxes.
6.Design a class Coordinate that represents a point in 2D space with x and y coordinates.
Overload the - operator to find the difference between two points.
7.Design a class Matrix that represents a 2x2 matrix. Overload the + operator to allow the
addition of two matrices.
8.Create a class ComplexNumber that represents complex numbers. Overload the * operator
to allow the multiplication of two complex numbers.
9.Construct a class Polynomial representing a polynomial of the form ax^2 + bx + c.
Overload the () operator, allowing the polynomial to be called as a function to evaluate it at a
certain x-value.
10.Design a class Time that represents time in hours and minutes. Overload the + operator to
allow the addition of two time objects, and make sure it correctly handles situations where
minutes exceed 60.
11.Construct a class SetOfStacks that simulates several stacks. Each stack can hold a limited
number of elements. When one stack fills up, a new stack is created. Overload the <<
operator to push elements into the stack, ensuring that stacks do not exceed their capacity.
12.Design a class Vector3D that represents a 3D vector with x, y, and z components.
Overload the - operator to compute the difference between two vectors and the * operator to
compute the dot product.
Page 66 of 70
13.Design a class StringManipulator that holds a string. Overload the / operator such that it
splits the string by another string passed to it.
14.Create a class Polygon that represents a polygon through a list of (x, y) coordinates.
Overload the & operator to find the intersection of two polygons.
15.Design a class SafeList that extends the behavior of a regular list but overloads the []
operator (using __getitem__ and __setitem__). When trying to access an index out of range,
it should print an error message instead of throwing an exception.
16.Design a class SparseVector to represent vectors where most of the elements are zero.
Overload the * operator to compute the dot product between two sparse vectors efficiently.
17.Develop a class Matrix that represents a 2x2 matrix. Overload the ** operator to raise the
matrix to a given power using matrix multiplication.
18.Design a class Polynomial representing a polynomial. Overload the // operator to compute
the derivative of the polynomial.
19.Design a class Currency that represents a specific amount of money in a given currency
(e.g., USD, EUR). Overload the + and - operators to allow operations between instances of
the same currency. If an operation is attempted between different currencies, print an error
message.
20.Develop a class TimeInterval that represents a period of time in hours, minutes, and
seconds. Overload the % operator to compute the remainder of dividing two time intervals.
21.Construct a class Fraction that represents a fraction. Overload the ~ operator to compute
the reciprocal of the fraction.
STATIC METHOD
1.Design a class MathUtility that has a static method to compute the factorial of a number.
2.Design a class TemperatureConverter that has static methods to convert temperatures
between Celsius and Fahrenheit.
3.Create a class StringAnalyzer that has a static method to check if a given string is a
palindrome (ignores cases, spaces, and punctuation).
4.Construct a class Calculator with static methods to perform basic arithmetic operations:
addition, subtraction, multiplication, and division.
5.Design a class DateValidator that has a static method to check if a given date in the format
YYYY-MM-DD is valid or not.
6.Create a class NumberUtility that provides a static method to determine if a number is even
or odd.
7.Design a class BinaryOps that has static methods to perform bitwise operations (AND, OR,
XOR) on two given binary strings of equal lengths.
Page 67 of 70
8.Design a class FileUtility that provides static methods to read and write to a file. The write
method should append to a file if it exists or create a new one otherwise.
9.Construct a class Fibonacci that offers a static method to generate the Fibonacci sequence
up to a given number or for a given number of terms.
10.Create a class PrimeUtility that provides a static method to determine if a number is prime
and another to retrieve the nth prime number.
11.Design a class Geometry that offers static methods to calculate the area of different
geometric shapes like a circle, rectangle, and triangle.
12.Develop a class DateOperations that provides static methods to determine the number of
days between two dates without using any external libraries. (Assume each month has 30
days for simplicity).
13.Design a class LRUCache (Least Recently Used Cache) that provides methods for
accessing and updating a cache with a limited size. When the cache is full, it should evict the
least recently accessed item.
14.Develop a class BigInt that can handle very large integer numbers (larger than the typical
64-bit integer) by storing them as strings. Provide static methods for basic arithmetic
operations like addition and multiplication.
15.Design a class BaseConverter that provides a static method to convert numbers from one
base to another (between bases 2 and 16).
16.Create a class StringPattern that provides a static method to find all occurrences of a
pattern within a given string using the Knuth-Morris-Pratt (KMP) algorithm.
17.Design a class MathematicalExpressions that provides a static method to evaluate
mathematical expressions given in string format using the Shunting Yard algorithm.
18.Develop a class CircularPrimes that provides a static method to count the number of
circular primes below a given number. A circular prime is a prime number that remains prime
under cyclic shifts of its digits.
19.Design a class GraphAlgorithms that provides a static method to determine if a given
directed graph has a cycle. The graph will be represented as an adjacency list.
20.Construct a class BigIntegerOperations that provides a static method to compute the
greatest common divisor (GCD) of two large integers represented as strings.
21.Design a class WordLadder that offers a static method to find the shortest transformation
sequence from a source word to a target word by changing only one letter at a time such that
each transformed word must exist in a given word list.
PROPERTY DECORTOR
1.Design a class Circle that has a private radius. Use property decorators to create getter and
setter methods for the radius, ensuring the radius cannot be set to a negative value.
Page 68 of 70
2.Design a class Rectangle that has private width and height attributes. Use property
decorators to create getter and setter methods for both attributes, ensuring neither can be set
to a negative value. Also, add a property for calculating the area.
3.Design a class BankAccount that has a private balance attribute. Use property decorators to
create a getter for the balance, ensuring that it cannot be set directly but only modified
through methods like deposit and withdraw.
4.Design a class Temperature that maintains a temperature in Celsius. Use property
decorators to get and set temperatures in Fahrenheit, ensuring proper conversion between
Celsius and Fahrenheit.
5.Design a class Employee with private attributes: _salary and _bonus. The bonus cannot
exceed 20% of the salary. Use property decorators to control access and modifications to
these attributes.
6.Design a class Square that has a side attribute. Also, make properties for area and perimeter
of the square. Ensure that when the side of the square is set, the area and perimeter change
accordingly.
7.Design a class BankAccount where the balance cannot go below a minimum balance. If a
withdrawal request would make the balance go below this limit, it should be denied.
8.Design a class Smartphone with attributes _storage_used and _total_storage. Implement
properties to get available storage and storage used as percentages.
9.Create a class Cube that has a _side attribute. Implement properties for volume and surface
area of the cube. Ensure the volume and surface area adjust correctly when the side of the
cube changes.
10.Design a class Fraction that represents a mathematical fraction. Implement properties to
get the fraction in reduced form (e.g., 8/24 should be represented as 1/3).
11.Design a class Time that maintains time in hours, minutes, and seconds. Implement
properties to set time in seconds and get time in hours, minutes, and seconds format.
12.Develop a class SafeList that extends the list but with an additional property to set and get
the sum of the list elements. When setting the sum, it should update the last element of the list
to ensure the total matches the set sum.
13.Design a class VirtualFileSystem which simulates a simple file system with a certain total
size. The file system has files of variable sizes and should ensure that the total used space
doesn't exceed its capacity. Use properties to manage the space allocation.
14.Design a class Reservoir to simulate a water reservoir. Implement properties to handle the
inflow and outflow of the water, ensuring that the reservoir does not overfill or become
negative.
15.Develop a class EBook that represents a digital book. It should have properties for the
total pages, current page, and a method to "turn" pages forward and backward. Ensure
boundary conditions, i.e., not going below the first page or beyond the last page.
Page 69 of 70
ENCAPSULATION
1.Design a class BankAccount that has a private balance. Implement methods to deposit,
withdraw, and check balance. Ensure the balance never goes negative.
2.Create a class Student with private attributes for name and age. Implement public methods
to get and set the name and age, ensuring age is between 5 and 25.
3.Design a class Laptop that has a private attribute for battery life (in percentage). Create
methods to charge the laptop and use it, ensuring the battery percentage stays between 0 and
100.
4.Design a class SafeList that extends Python's list. This class should override the append
method to ensure that only integer values can be added to the list.
5.Design a class UserProfile that has private attributes for username and password.
Implement methods to get and set the username and password. Password setting should
ensure that it's at least 8 characters long.
6.Develop a class Library that manages books. It should have private lists for available and
issued books. Implement methods to issue, return, and check the status of a book.
7.Design a class LimitedSizeList that behaves like a list but has a maximum size. If elements
are added beyond this size, the oldest elements should be removed to maintain the size limit.
8.Design a class PrivateAttributes that uses name mangling to keep all its attributes private. It
should also override the default behavior of the dir() function to hide private attributes.
9.Design a class SecureDatabase that maintains key-value pairs. It should provide methods to
add, get, and delete key-value pairs. However, to access these methods, a user password
should be provided, and it should match the one set during initialization.
Page 70 of 70