0% found this document useful (0 votes)
4 views

CS practical file non cover

The document outlines a series of programming problems defined for a student named Soham Surana, covering various mathematical functions such as generating patterns, checking for palindromic and prime numbers, calculating HCF, and determining perfect and amicable numbers. Each problem includes a function definition, its purpose, and sample outputs. The document emphasizes efficiency and user-friendliness in the implementation of these functions.

Uploaded by

ry341892
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

CS practical file non cover

The document outlines a series of programming problems defined for a student named Soham Surana, covering various mathematical functions such as generating patterns, checking for palindromic and prime numbers, calculating HCF, and determining perfect and amicable numbers. Each problem includes a function definition, its purpose, and sample outputs. The document emphasizes efficiency and user-friendliness in the implementation of these functions.

Uploaded by

ry341892
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

# Problem/Program Number: 1, Date: 29-05-2024

"""
Problem Definition:
Define a function Pattern(N) that displays a pattern in the shape of a pyramid.
The pattern should start with 1 at the top and increase in length down to N rows.
Each row i (where i ranges from 1 to N) should contain numbers starting from i,
counting down to 1, and then back up to i.

For example, for N=4, the pattern should be:


1
212
32123
4321234

The program should be efficient and user-friendly.


"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def pattern(N):
"""
Function to display the pyramid pattern as described in the problem definition.
N: int - The number of rows in the pyramid.
"""
# Loop through the number of rows
for i in range(1, N + 1):
# Print leading spaces for alignment
print(' ' * (N - i), end='')

# Print decreasing part of the pattern


for j in range(i, 0, -1):
print(j, end='')

# Print increasing part of the pattern


for j in range(2, i + 1):
print(j, end='')

# Move to the next line after each row is printed


print()

# Call the pattern function with N = 5


pattern(5)

# Sample Output:
# 1
# 212
# 32123
# 4321234
# 543212345

# Problem/Program Number: 2, Date: 29-05-2024

"""
Problem Definition:
Define a function isPalindrome(N) that checks whether N is a Palindromic number
or not.
A Palindromic number reads the same forwards and backwards, such as 121 or
1331.
If the number is Palindromic, the function should return 1; otherwise, it should
return 0.
Using this function, write a program to display all Palindromic numbers between 1
and 1000.

The program should be efficient and user-friendly.


"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def is_palindrome(N):
"""
Function to check if a number N is a Palindromic number.
N: int - The number to check.
Returns: int - 1 if the number is Palindromic, otherwise 0.
"""
# Convert the number to a string
num_str = str(N)

# Check if the string reads the same forwards and backwards


if num_str == num_str[::-1]:
return 1
else:
return 0

def display_palindromic_numbers():
"""
Function to display all Palindromic numbers between 1 and 1000.
"""
print("Palindromic numbers between 1 and 1000 are:")
for num in range(1, 1001):
if is_palindrome(num):
print(num, end=' ')
print()

# Call the function to display Palindromic numbers between 1 and 1000


display_palindromic_numbers()

# Sample Output:
# Palindromic numbers between 1 and 1000 are:
# 1 2 3 4 5 6 7 8 9 11 22 33 44 55 66 77 88 99 101 111 121 131 141 151 161
171 181 191 202 212 222 232 242 252 262 272 282 292 303 313 323 333 343
353 363 373 383 393 404 414 424 434 444 454 464 474 484 494 505 515 525
535 545 555 565 575 585 595 606 616 626 636 646 656 666 676 686 696 707
717 727 737 747 757 767 777 787 797 808 818 828 838 848 858 868 878 888
898 909 919 929 939 949 959 969 979 989 999

# Problem/Program Number: 3, Date: 31-05-2024

"""
Problem Definition:
Define a function isPrime(N) that checks whether N is a prime number or not.
A prime number is a natural number greater than 1 that has no positive divisors
other than 1 and itself.
If the number is prime, the function should return 1; otherwise, it should return
0.
Using this function, write a program to display all prime numbers between 1 and
100.

The program should be efficient and user-friendly.


"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def is_prime(N):
"""
Function to check if a number N is a prime number.
N: int - The number to check.
Returns: int - 1 if the number is prime, otherwise 0.
"""
if N <= 1:
return 0
for i in range(2, int(N ** 0.5) + 1):
if N % i == 0:
return 0
return 1

def display_prime_numbers():
"""
Function to display all prime numbers between 1 and 100.
"""
print("Prime numbers between 1 and 100 are:")

for num in range(1, 101):


if is_prime(num):
print(num, end=' ')
print()

# Call the function to display prime numbers between 1 and 100


display_prime_numbers()

# Sample Output:
# Prime numbers between 1 and 100 are:
# 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

# Problem/Program Number: 4, Date: 01-06-2024

"""
Problem Definition:
Define a function HCF(A, B) that calculates and returns the Highest Common
Factor (HCF) or
Greatest Common Divisor (GCD) of two numbers A and B.
The HCF of two numbers is the largest number that divides both of them without
leaving a remainder.
Using this function, write a program to check whether two user-inputted numbers
M and N are co-prime or not.
Two numbers are co-prime if their HCF is 1.

The program should be efficient and user-friendly.


"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def hcf(A, B):


"""
Function to calculate the HCF/GCD of two numbers A and B.
A, B: int - The numbers for which HCF is to be calculated.
Returns: int - The HCF of A and B.
"""
while B:
A, B = B, A % B
return A

def check_co_prime(M, N):


"""
Function to check if two numbers M and N are co-prime.
M, N: int - The numbers to check.
Prints whether M and N are co-prime or not based on their HCF.
"""
if hcf(M, N) == 1:
print(f"{M} and {N} are co-prime.")
else:
print(f"{M} and {N} are not co-prime.")

# User inputs for numbers M and N


M = int(input("Enter the first number (M): "))
N = int(input("Enter the second number (N): "))

# Check and display whether M and N are co-prime


check_co_prime(M, N)

# Sample Output:
# Enter the first number (M): 15
# Enter the second number (N): 28
# 15 and 28 are co-prime.

# Problem/Program Number: 5, Date: 01-06-2024

"""
Problem Definition:
Define a function SumOfFactors(N) that calculates and returns the sum of all
proper factors of N.
Proper factors include all factors of N except the number N itself (but including 1).
Using this function, write a program to check whether a user-inputted number M
is a perfect number or not.
A perfect number is a number that is equal to the sum of its proper factors.

The program should be efficient and user-friendly.


"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def SumOfFactors(N):
"""
Function to calculate the sum of all proper factors of a number N.
N: int - The number for which the proper factors' sum is to be calculated.
Returns: int - The sum of all proper factors of N.
"""
sum_factors = 0

# Iterate through all numbers from 1 to N/2


for i in range(1, N // 2 + 1):
if N % i == 0:
sum_factors += i

return sum_factors

def check_perfect_number(M):
"""
Function to check if a number M is a perfect number.
M: int - The number to check.
Prints whether M is a perfect number or not based on the sum of its proper
factors.
"""
if SumOfFactors(M) == M:
print(f"{M} is a perfect number.")
else:
print(f"{M} is not a perfect number.")

# User input for number M


M = int(input("Enter a number (M): "))

# Check and display whether M is a perfect number


check_perfect_number(M)

# Sample Output:
# Enter a number (M): 28
# 28 is a perfect number.

# Problem/Program Number: 6, Date: 02-06-2024

"""
Problem Definition:
Define a function SumOfFactors(N) that calculates and returns the sum of all
proper factors of N.
Proper factors include all factors of N except the number N itself (but including 1).
Using this function, write a program to check whether two user-inputted numbers
A and B are amicable or not.
Two numbers A and B are called amicable if the sum of the proper factors of A is
equal to B, and
the sum of the proper factors of B is equal to A.
The program should be efficient and user-friendly.
"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def SumOfFactors(N):
"""
Function to calculate the sum of all proper factors of a number N.
N: int - The number for which the proper factors' sum is to be calculated.
Returns: int - The sum of all proper factors of N.
"""
sum_factors = 0

# Iterate through all numbers from 1 to N/2


for i in range(1, N // 2 + 1):
if N % i == 0:
sum_factors += i

return sum_factors

def check_amicable_numbers(A, B):


"""
Function to check if two numbers A and B are amicable.
A, B: int - The numbers to check.
Prints whether A and B are amicable based on the sum of their proper factors.
"""
if SumOfFactors(A) == B and SumOfFactors(B) == A:
print(f"{A} and {B} are amicable numbers.")
else:
print(f"{A} and {B} are not amicable numbers.")

# User inputs for numbers A and B


A = int(input("Enter the first number (A): "))
B = int(input("Enter the second number (B): "))

# Check and display whether A and B are amicable numbers


check_amicable_numbers(A, B)

# Sample Output:
# Enter the first number (A): 220
# Enter the second number (B): 284
# 220 and 284 are amicable numbers.

# Problem/Program Number: 7, Date: 02-06-2024


"""
Problem Definition:
Define a recursive function Factorial(N) that calculates and returns the factorial of
a number N.
The factorial of a number N (denoted as N!) is the product of all positive integers
less than or equal to N.
Using this function, write a program to display the factorial of the first 5 natural
numbers.

The program should be efficient and user-friendly.


"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def Factorial(N):
"""
Recursive function to calculate the factorial of a number N.
N: int - The number for which the factorial is to be calculated.
Returns: int - The factorial of N.
"""
if N == 1 or N == 0: # Base case: factorial of 0 or 1 is 1
return 1
else:
return N * Factorial(N - 1) # Recursive case

def display_factorials():
"""
Function to display the factorial of the first 5 natural numbers.
"""
for i in range(1, 6):
print(f"The factorial of {i} is: {Factorial(i)}")

# Display the factorial of the first 5 natural numbers


display_factorials()

# Sample Output:
# The factorial of 1 is: 1
# The factorial of 2 is: 2
# The factorial of 3 is: 6
# The factorial of 4 is: 24
# The factorial of 5 is: 120

# Problem/Program Number: 8, Date: 02-06-2024


"""
Problem Definition:
Define a recursive function Fibonacci(N) that calculates and returns the Nth
member of the Fibonacci series.
The Fibonacci series is a sequence of numbers where each number is the sum of
the two preceding ones,
starting from 0 and 1. That is, Fibonacci(0) = 0, Fibonacci(1) = 1, and
Fibonacci(N) = Fibonacci(N-1) + Fibonacci(N-2) for N > 1.
Using this function, write a program to display the first 20 Fibonacci numbers.

The program should be efficient and user-friendly.


"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def Fibonacci(N):
"""
Recursive function to calculate the Nth Fibonacci number.
N: int - The position in the Fibonacci sequence for which the number is to be
calculated.
Returns: int - The Nth Fibonacci number.
"""
if N == 0: # Base case: Fibonacci(0) is 0
return 0
elif N == 1: # Base case: Fibonacci(1) is 1
return 1
else:
return Fibonacci(N - 1) + Fibonacci(N - 2) # Recursive case

def display_fibonacci_series():
"""
Function to display the first 20 Fibonacci numbers.
"""
for i in range(20):
print(f"Fibonacci({i}) = {Fibonacci(i)}")

# Display the first 20 Fibonacci numbers


display_fibonacci_series()

# Sample Output:
# Fibonacci(0) = 0
# Fibonacci(1) = 1
# Fibonacci(2) = 1
# Fibonacci(3) = 2
# Fibonacci(4) = 3
# Fibonacci(5) = 5
# Fibonacci(6) = 8
# Fibonacci(7) = 13
# Fibonacci(8) = 21
# Fibonacci(9) = 34
# Fibonacci(10) = 55
# Fibonacci(11) = 89
# Fibonacci(12) = 144
# Fibonacci(13) = 233
# Fibonacci(14) = 377
# Fibonacci(15) = 610
# Fibonacci(16) = 987
# Fibonacci(17) = 1597
# Fibonacci(18) = 2584
# Fibonacci(19) = 4181

# Problem/Program Number: 9, Date: 02-06-2024


Program for Series 1: 1+x+x2+x3+x4+⋯+xn

"""
Problem Definition:
Define functions Pow(X, N) and Factorial(N) to calculate and return X^N and N!
respectively.
Using these functions, write a program to calculate and display the sum of the
series:
1 + x + x^2 + x^3 + x^4 + ... + x^n
The program should be efficient and user-friendly.
"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def Pow(X, N):


"""
Function to calculate X raised to the power N (X^N).
X: int/float - The base number.
N: int - The exponent.
Returns: int/float - The result of X^N.
"""
return X ** N

def sum_series_1(X, N):


"""
Function to calculate the sum of the series 1 + X + X^2 + X^3 + ... + X^N.
X: int/float - The base number.
N: int - The number of terms in the series.
Returns: int/float - The sum of the series.
"""
sum_series = 0
for i in range(N + 1):
sum_series += Pow(X, i)
return sum_series

# User inputs
X = float(input("Enter the value of X: "))
N = int(input("Enter the value of N: "))

# Calculate and display the sum of the series


print(f"The sum of the series is: {sum_series_1(X, N)}")

Program for Series 2: 1−x+x2−x3+x4−⋯±xn


# Problem/Program Number: 1, Date: 02-06-2024

"""
Problem Definition:
Define functions Pow(X, N) and Factorial(N) to calculate and return X^N and N!
respectively.
Using these functions, write a program to calculate and display the sum of the
series:
1 - x + x^2 - x^3 + x^4 - ... ± x^n
The program should be efficient and user-friendly.
"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def sum_series_2(X, N):


"""
Function to calculate the sum of the series 1 - X + X^2 - X^3 + ... ± X^N.
X: int/float - The base number.
N: int - The number of terms in the series.
Returns: int/float - The sum of the series.
"""
sum_series = 0
for i in range(N + 1):
sum_series += Pow(X, i) * (-1) ** i
return sum_series

# Calculate and display the sum of the series


print(f"The sum of the series is: {sum_series_2(X, N)}")

Program for Series 3: x+x2/2−x3/3 + x4/4⋯(±)xn/n


# Problem/Program Number: 1, Date: 02-06-2024

"""
Problem Definition:
Define functions Pow(X, N) and Factorial(N) to calculate and return X^N and N!
respectively.
Using these functions, write a program to calculate and display the sum of the
series:
X + X^2/2 - X^3/3 + X^4/4 ... ± X^N/N
The program should be efficient and user-friendly.
"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def sum_series_3(X, N):


"""
Function to calculate the sum of the series X + X^2/2 - X^3/3 + ... ± X^N/N.
X: int/float - The base number.
N: int - The number of terms in the series.
Returns: int/float - The sum of the series.
"""
sum_series = 0
for i in range(1, N + 1):
sum_series += Pow(X, i) * (-1) ** (i + 1) / i
return sum_series

# Calculate and display the sum of the series


print(f"The sum of the series is: {sum_series_3(X, N)}")

Program for Series 4: x+x2/2!−x3/3!+x4/4!…(±)xn/n!


# Problem/Program Number: 1, Date: 02-06-2024

"""
Problem Definition:
Define functions Pow(X, N) and Factorial(N) to calculate and return X^N and N!
respectively.
Using these functions, write a program to calculate and display the sum of the
series:
X + X^2/2! - X^3/3! + X^4/4! ... ± X^N/N!
The program should be efficient and user-friendly.
"""

# Name of the Student: Soham Surana, Class: S7, Section: C

def Factorial(N):
"""
Function to calculate the factorial of a number N (N!).
N: int - The number for which the factorial is to be calculated.
Returns: int - The factorial of N.
"""
if N == 0 or N == 1:
return 1
else:
return N * Factorial(N - 1)

def sum_series_4(X, N):


"""
Function to calculate the sum of the series X + X^2/2! - X^3/3! + ... ±
X^N/N!.
X: int/float - The base number.
N: int - The number of terms in the series.
Returns: int/float - The sum of the series.
"""
sum_series = 0
for i in range(1, N + 1):
sum_series += Pow(X, i) * (-1) ** (i + 1) / Factorial(i)
return sum_series

# Calculate and display the sum of the series


print(f"The sum of the series is: {sum_series_4(X, N)}")

# Problem/Program Number:10 Date: 05-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
The goal of this program is to encode a word by applying the following steps:
1. Convert lower case alphabets into upper case and vice versa. Non-alphabetic
characters remain unchanged.
2. Swap the first character with the second, the third with the fourth, and so on.
If the word has an odd number of characters, the last character remains in place.

The program reads a sentence from the user, encodes each word using the above
method, and then displays the encrypted sentence.

The program includes proper naming conventions, comments, and user-friendly


interactions.
"""

def encode(word):
# Step 1: Change the case of each alphabet
transformed_word = ''.join([char.lower() if char.isupper() else char.upper() for
char in word])

# Step 2: Swap characters in pairs


encoded_word = []
length = len(transformed_word)

for i in range(0, length - 1, 2):


# Swap adjacent characters
encoded_word.append(transformed_word[i + 1])
encoded_word.append(transformed_word[i])

if length % 2 != 0:
# If the word has an odd number of characters, append the last character
encoded_word.append(transformed_word[-1])

# Join the list into a single string and return


return ''.join(encoded_word)

# Main function to process a sentence


def process_sentence(sentence):
# Split the sentence into words
words = sentence.split()
# Encode each word
encoded_words = [encode(word) for word in words]
# Join the encoded words into a single sentence
return ' '.join(encoded_words)

# Read a sentence from the user


user_sentence = input("Enter a sentence to encode: ")

# Encode the sentence


encoded_sentence = process_sentence(user_sentence)

# Display the result


print("Encoded sentence:", encoded_sentence)

# Sample Output:
# Input: "Hello World!"
# Output: "hElLo wOrLd!"

# Problem/Program Number: 11 Date: 05-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program defines a function `isPalindrome(W)` that checks if a word W is
palindromic.
A word is considered a palindrome if it reads the same backward as forward. The
program
will create a list `SENTENCES` consisting of 5 sentences entered by the user and
display all palindromic words present in those sentences.
"""

def isPalindrome(word):
# Check if the word is the same when reversed
return word.lower() == word[::-1].lower()

# Main function to process sentences and find palindromic words


def find_palindromic_words(sentences):
palindromic_words = []
for sentence in sentences:
words = sentence.split()
for word in words:
if isPalindrome(word):
palindromic_words.append(word)
return palindromic_words

# Read 5 sentences from the user


SENTENCES = [input(f"Enter sentence {i+1}: ") for i in range(5)]

# Find and display palindromic words


palindromic_words = find_palindromic_words(SENTENCES)
print("Palindromic words found:", palindromic_words)

# Problem/Program Number: 12 Date: 05-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program defines a function `CountWord(S, W)` that counts and returns the
number of
occurrences of the word W in the sentence S. The program will create a list
`SENTENCES`
consisting of 5 sentences entered by the user and count the total number of
occurrences
of the word 'Modern' in those 5 sentences.
"""

def CountWord(sentence, word):


# Convert sentence to lowercase and split into words
words = sentence.lower().split()
# Count occurrences of the word
return words.count(word.lower())

# Main function to process sentences and count occurrences of 'Modern'


def count_total_occurrences(sentences, word):
total_count = 0
for sentence in sentences:
total_count += CountWord(sentence, word)
return total_count

# Read 5 sentences from the user


SENTENCES = [input(f"Enter sentence {i+1}: ") for i in range(5)]

# Count and display total occurrences of 'Modern'


word_to_count = 'Modern'
total_occurrences = count_total_occurrences(SENTENCES, word_to_count)
print(f"Total occurrences of the word '{word_to_count}':", total_occurrences)

# Problem/Program Number: 13 Date: 05-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program processes a list `SENTENCES` consisting of 5 sentences entered by
the user.
It filters and displays:
1. All words that start with 'A' or 'a' and are longer than 4 characters.
2. All words that end with 'A' or 'a' and are shorter than 4 characters.
"""

def filter_words(sentences):
start_with_a_longer_than_4 = []
end_with_a_shorter_than_4 = []

for sentence in sentences:


words = sentence.split()
for word in words:
# Check if the word starts with 'A' or 'a' and is longer than 4 characters
if (word.lower().startswith('a') and len(word) > 4):
start_with_a_longer_than_4.append(word)

# Check if the word ends with 'A' or 'a' and is shorter than 4 characters
if (word.lower().endswith('a') and len(word) < 4):
end_with_a_shorter_than_4.append(word)

return start_with_a_longer_than_4, end_with_a_shorter_than_4

# Read 5 sentences from the user


SENTENCES = [input(f"Enter sentence {i+1}: ") for i in range(5)]

# Filter words based on the criteria


start_with_a_longer_than_4, end_with_a_shorter_than_4 =
filter_words(SENTENCES)

# Display the filtered words


print("Words that start with 'A' or 'a' and are longer than 4 characters:",
start_with_a_longer_than_4)
print("Words that end with 'A' or 'a' and are shorter than 4 characters:",
end_with_a_shorter_than_4)

# Problem/Program Number: 14 Date: 08-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program provides a menu-based interface to perform tasks on a Python list
`NUMBERS`.
The tasks include:
1. Adding a new number to the list.
2. Displaying all numbers in the list.
3. Sorting the list in descending order using the bubble sort technique.

The program defines a function for bubble sorting and ensures user-friendly
interactions.
"""

# Sample List of Numbers


NUMBERS = [12, 33, 13, 54, 34, 57]

def bubble_sort_descending(numbers):
# Perform bubble sort in descending order
n = len(numbers)
for i in range(n):
for j in range(0, n-i-1):
if numbers[j] < numbers[j+1]:
numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
return numbers

def add_number():
# Add a new number to the list
new_number = int(input("Enter a new number to add: "))
NUMBERS.append(new_number)
print(f"{new_number} has been added to the list.")

def display_numbers():
# Display all numbers in the list
print("Numbers in the list:", NUMBERS)

def sort_numbers():
# Sort the list in descending order
sorted_numbers = bubble_sort_descending(NUMBERS.copy())
print("Numbers sorted in descending order:", sorted_numbers)

# Main menu-driven program


while True:
print("\nMenu:")
print("1. Add a new number")
print("2. Display all numbers")
print("3. Sort numbers in descending order")
print("4. Exit")
choice = input("Enter your choice (1-4): ")

if choice == '1':
add_number()
elif choice == '2':
display_numbers()
elif choice == '3':
sort_numbers()
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

# Problem/Program Number: 15 Date: 08-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program provides a menu-based interface to perform tasks on a Python list
`WORDS`.
The tasks include:
1. Adding a new word to the list.
2. Displaying all words in the list.
3. Sorting the list alphabetically using the insertion sort technique.

The program defines a function for insertion sorting and ensures user-friendly
interactions.
"""

# Sample List of Words


WORDS = ['LAN', 'MAN', 'WAN', 'VoIP', 'HTTPS']
def insertion_sort_alphabetical(words):
# Perform insertion sort alphabetically
for i in range(1, len(words)):
key = words[i]
j=i-1
while j >= 0 and key < words[j]:
words[j + 1] = words[j]
j -= 1
words[j + 1] = key
return words

def add_word():
# Add a new word to the list
new_word = input("Enter a new word to add: ")
WORDS.append(new_word)
print(f"'{new_word}' has been added to the list.")

def display_words():
# Display all words in the list
print("Words in the list:", WORDS)

def sort_words():
# Sort the list alphabetically
sorted_words = insertion_sort_alphabetical(WORDS.copy())
print("Words sorted alphabetically:", sorted_words)

# Main menu-driven program


while True:
print("\nMenu:")
print("1. Add a new word")
print("2. Display all words")
print("3. Sort words alphabetically")
print("4. Exit")
choice = input("Enter your choice (1-4): ")

if choice == '1':
add_word()
elif choice == '2':
display_words()
elif choice == '3':
sort_words()
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

# Problem/Program Number: 16 Date: 08-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program defines a function `LSearch(ARR, DATA)` that checks whether the
list of numbers `ARR`
contains the searched number `DATA` using the linear search technique.
The function returns 1 if `DATA` is found, otherwise, it returns 0.

The program tests the function with sample values and ensures user-friendly
interactions.
"""

# Sample List of Numbers


NUMBERS = [12, 13, 33, 34, 54, 57]

def LSearch(ARR, DATA):


# Perform linear search to check if DATA is in ARR
for number in ARR:
if number == DATA:
return 1
return 0

# Test the function with sample values


DATA = int(input("Enter the number to search for: "))
result = LSearch(NUMBERS, DATA)

if result == 1:
print(f"The number {DATA} is present in the list.")
else:
print(f"The number {DATA} is not present in the list.")

# Problem/Program Number: 17 Date: 08-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program defines a function `bSearch(ARR, DATA)` that checks whether the
list of numbers `ARR`
contains the searched number `DATA` using the Binary Search Technique.
The function returns 1 if `DATA` is found, otherwise, it returns 0.
The program tests the function with sample values and ensures user-friendly
interactions.
"""

# Sample List of Numbers


NUMBERS = [12, 13, 33, 34, 54, 57]

def bSearch(ARR, DATA):


# Perform binary search on a sorted list
left, right = 0, len(ARR) - 1
while left <= right:
mid = (left + right) // 2
if ARR[mid] == DATA:
return 1
elif ARR[mid] < DATA:
left = mid + 1
else:
right = mid - 1
return 0

# Test the function with sample values


DATA = int(input("Enter the number to search for: "))
result = bSearch(NUMBERS, DATA)

if result == 1:
print(f"The number {DATA} is present in the list.")
else:
print(f"The number {DATA} is not present in the list.")

# Problem/Program Number: 18 Date: 08-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program implements a menu-driven interface for performing stack-based
operations (LIFO)
on a list `STUDENTS` that stores the names and marks of students.
The tasks include:
1. Adding a new student to the list.
2. Displaying all students' names and marks.
3. Removing the last student from the list and displaying their details.

The program handles errors and provides user-friendly feedback.


"""

# Sample List of Students


STUDENTS = [['Raghav', 89], ['Rohan', 90], ['Amrita', 91]]

def add_student():
# Add a new student to the list
name = input("Enter the student's name: ")
marks = int(input("Enter the student's marks: "))
STUDENTS.append([name, marks])
print(f"Student '{name}' with marks {marks} has been added to the list.")

def display_students():
# Display all students in the list
print("Students and their marks:")
for student in STUDENTS:
print(f"Name: {student[0]}, Marks: {student[1]}")

def remove_student():
# Remove the last student from the list (LIFO)
if STUDENTS:
removed_student = STUDENTS.pop()
print(f"Removed student: Name: {removed_student[0]}, Marks:
{removed_student[1]}")
else:
print("No students left to remove.")

# Main menu-driven program


while True:
print("\nMenu:")
print("1. Add a new student")
print("2. Display all students")
print("3. Remove the last student")
print("4. Exit")
choice = input("Enter your choice (1-4): ")

if choice == '1':
add_student()
elif choice == '2':
display_students()
elif choice == '3':
remove_student()
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

# Problem/Program Number: 19 Date: 08-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program implements a menu-driven interface for performing queue-based
operations (FIFO)
on a list `PERSONS` that stores the names and ages of persons.
The tasks include:
1. Adding a new person to the list.
2. Displaying all persons' names and ages.
3. Removing the first person from the list and displaying their details.

The program handles errors and provides user-friendly feedback.


"""

# Sample List of Persons


PERSONS = [['Rahamat', 18], ['Rajeev', 19], ['Amos', 17]]

def add_person():
# Add a new person to the list
name = input("Enter the person's name: ")
age = int(input("Enter the person's age: "))
PERSONS.append([name, age])
print(f"Person '{name}' with age {age} has been added to the list.")

def display_persons():
# Display all persons in the list
print("Persons and their ages:")
for person in PERSONS:
print(f"Name: {person[0]}, Age: {person[1]}")

def remove_person():
# Remove the first person from the list (FIFO)
if PERSONS:
removed_person = PERSONS.pop(0)
print(f"Removed person: Name: {removed_person[0]}, Age:
{removed_person[1]}")
else:
print("No persons left to remove.")

# Main menu-driven program


while True:
print("\nMenu:")
print("1. Add a new person")
print("2. Display all persons")
print("3. Remove the first person")
print("4. Exit")
choice = input("Enter your choice (1-4): ")

if choice == '1':
add_person()
elif choice == '2':
display_persons()
elif choice == '3':
remove_person()
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

# Problem/Program Number: 20 Date: 08-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program defines a function `Separate(NUMBERS)` that accepts a tuple
`NUMBERS` containing natural
numbers as an argument and separates it into two tuples: `EVEN` for even
numbers and `ODD` for odd numbers.
The tasks include:
1. Adding a new entry to the tuple `NUMBERS`.
2. Displaying all entries stored in the tuple `NUMBERS`.
3. Separating the tuple using the defined function and displaying the two newly
created tuples `EVEN` and `ODD`.
"""

def Separate(NUMBERS):
EVEN = tuple(num for num in NUMBERS if num % 2 == 0)
ODD = tuple(num for num in NUMBERS if num % 2 != 0)
return EVEN, ODD

# Initial Tuple
NUMBERS = (12, 33, 13, 54, 34, 57)

# Task 1: Add a new entry to the Tuple NUMBERS


new_entry = int(input("Enter a new number to add to the tuple: "))
NUMBERS = NUMBERS + (new_entry,)

# Task 2: Display all entries in the Tuple NUMBERS


print("Updated Tuple NUMBERS:", NUMBERS)
# Task 3: Separate the Tuple NUMBERS and display EVEN and ODD tuples
EVEN, ODD = Separate(NUMBERS)
print("EVEN numbers Tuple:", EVEN)
print("ODD numbers Tuple:", ODD)

# Problem/Program Number: 21 Date: 08-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program defines a function `GRADES(EMPLOYEES)` that accepts a dictionary
`EMPLOYEES` as an argument and
separates it into two dictionaries: `GradeA` for employees with a salary above
25000 and `GradeB` for those with a
salary of 25000 or below.
The tasks include:
1. Adding a new entry to the dictionary `EMPLOYEES`.
2. Displaying all entries stored in the dictionary `EMPLOYEES`.
3. Separating the dictionary using the defined function and displaying the two
newly created dictionaries `GradeA` and `GradeB`.
"""

def GRADES(EMPLOYEES):
GradeA = {name: salary for name, salary in EMPLOYEES.items() if salary >
25000}
GradeB = {name: salary for name, salary in EMPLOYEES.items() if salary <=
25000}
return GradeA, GradeB

# Initial Dictionary
EMPLOYEES = {'John': 18000, 'Rahim': 24000, 'Anita': 31000}

# Task 1: Add a new entry to the Dictionary EMPLOYEES


name = input("Enter the employee's name: ")
salary = int(input(f"Enter {name}'s salary: "))
EMPLOYEES[name] = salary

# Task 2: Display all entries in the Dictionary EMPLOYEES


print("Updated Dictionary EMPLOYEES:", EMPLOYEES)

# Task 3: Separate the Dictionary EMPLOYEES and display GradeA and GradeB
dictionaries
GradeA, GradeB = GRADES(EMPLOYEES)
print("GradeA (Salary > 25000):", GradeA)
print("GradeB (Salary <= 25000):", GradeB)
# Problem/Program Number: 22 Date: 08-06-2024
# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program defines a function `FREQTable(T)` that accepts a tuple `T`
containing natural numbers and creates
a frequency table in the form of a dictionary `FT` where keys are the numbers
from the tuple, and values are their frequencies.
The function returns the dictionary `FT`.
"""

def FREQTable(T):
FT = {}
for num in T:
if num in FT:
FT[num] += 1
else:
FT[num] = 1
return FT

# Sample Tuple
T = (4, 2, 6, 2, 4, 2, 4, 2)

# Create and display the Frequency Table


FT = FREQTable(T)
print("Frequency Table:", FT)

# Problem/Program Number: 23 Date: 08-06-2024


# Name of the Student: Soham Surana, Class: S7, Section: C

"""
Problem Definition:
This program defines a function `FREQTable(S)` that accepts a string `S`
representing a sentence.
The function creates a dictionary `FT` that stores the frequency of each character
in the string, excluding spaces.
It finally returns the dictionary `FT`.
"""

def FREQTable(S):
# Initialize an empty dictionary to store frequencies
FT = {}

# Loop through each character in the string


for char in S:
# Ignore spaces
if char != ' ':
# Update the frequency count in the dictionary
if char in FT:
FT[char] += 1
else:
FT[char] = 1

return FT

# Minimal program to use the defined function


# Input: Read a string from the user
S = input("Enter a sentence or word: ")

# Call the FREQTable function and store the result


frequency_table = FREQTable(S)

# Output: Display the frequency table


print("Frequency Table:", frequency_table)

# Problem/Program Number: 24 Date: 09-06-2024


Address Book – Solve the following:  Define a function to create a MySQL Table(Relation) having
following Columns(Attributes):  Name  Phone  Email  Define a function to append some
records into the table  Define a function to search for a record in the table – search by name  Define
a function to modify a record – search by name  Define a function to remove/delete a record from the
table – search by name  Write a menu based complete program to combine all the function defined
above.

import mysql.connector

def create_table():
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS AddressBook (
Name VARCHAR(255),
Phone VARCHAR(15),
Email VARCHAR(255)
)
""")
conn.close()

# Call the function to create the table


create_table()
def append_record(name, phone, email):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("INSERT INTO AddressBook (Name, Phone, Email) VALUES
(%s, %s, %s)", (name, phone, email))
conn.commit()
conn.close()
def search_record(name):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM AddressBook WHERE Name=%s", (name,))
record = cursor.fetchone()
conn.close()
return record
def modify_record(name, new_phone, new_email):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("UPDATE AddressBook SET Phone=%s, Email=%s WHERE
Name=%s", (new_phone, new_email, name))
conn.commit()
conn.close()

def delete_record(name):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("DELETE FROM AddressBook WHERE Name=%s", (name,))
conn.commit()
conn.close()

def menu():
while True:
print("\nAddress Book Menu")
print("1. Create Table")
print("2. Append Record")
print("3. Search Record")
print("4. Modify Record")
print("5. Delete Record")
print("6. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
create_table()
print("Table created successfully.")
elif choice == 2:
name = input("Enter Name: ")
phone = input("Enter Phone: ")
email = input("Enter Email: ")
append_record(name, phone, email)
print("Record added successfully.")
elif choice == 3:
name = input("Enter Name to search: ")
record = search_record(name)
if record:
print("Record Found: ", record)
else:
print("No record found.")
elif choice == 4:
name = input("Enter Name to modify: ")
new_phone = input("Enter New Phone: ")
new_email = input("Enter New Email: ")
modify_record(name, new_phone, new_email)
print("Record updated successfully.")
elif choice == 5:
name = input("Enter Name to delete: ")
delete_record(name)
print("Record deleted successfully.")
elif choice == 6:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

# Run the menu


menu()

“Blood Donor’s Database  Design a MySQL Table(Relation) having following Columns(Attributes)


of some volunteer Blood Donors:  AadhaarNo  BloodGroup  LDD # Last Date of Donation in
dd/mm/yyyy format  Name  DOB # Date of Birth in dd/mm/yyyy format  Address  District 
State  Country  MobileNo1  MobileNo2  Email Your program should have at least the
following user friendly options:  Create the Table & Add New Donor  Search a Donor by Blood
Group  Modify details of a Donor  Remove a donor from the file ”

def create_donor_table():
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS BloodDonors (
AadhaarNo VARCHAR(12) PRIMARY KEY,
BloodGroup VARCHAR(3),
LDD DATE,
Name VARCHAR(255),
DOB DATE,
Address TEXT,
District VARCHAR(100),
State VARCHAR(100),
Country VARCHAR(100),
MobileNo1 VARCHAR(15),
MobileNo2 VARCHAR(15),
Email VARCHAR(255)
)
""")
conn.close()
def add_donor(aadhaar, blood_group, ldd, name, dob, address, district, state,
country, mobile1, mobile2, email):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("""
INSERT INTO BloodDonors (AadhaarNo, BloodGroup, LDD, Name, DOB,
Address, District, State, Country, MobileNo1, MobileNo2, Email)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
""", (aadhaar, blood_group, ldd, name, dob, address, district, state, country,
mobile1, mobile2, email))
conn.commit()
conn.close()
def search_donor_by_blood_group(blood_group):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM BloodDonors WHERE BloodGroup=%s",
(blood_group,))
donors = cursor.fetchall()
conn.close()
return donors
def modify_donor(aadhaar, new_address, new_mobile1, new_mobile2):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("""
UPDATE BloodDonors SET Address=%s, MobileNo1=%s, MobileNo2=%s
WHERE AadhaarNo=%s
""", (new_address, new_mobile1, new_mobile2, aadhaar))
conn.commit()
conn.close()
def remove_donor(aadhaar):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("DELETE FROM BloodDonors WHERE AadhaarNo=%s",
(aadhaar,))
conn.commit()
conn.close()
def donor_menu():
while True:
print("\nBlood Donor's Database Menu")
print("1. Create Donor Table & Add New Donor")
print("2. Search Donor by Blood Group")
print("3. Modify Donor Details")
print("4. Remove a Donor")
print("5. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
create_donor_table()
print("Table created successfully.")
aadhaar = input("Enter Aadhaar Number: ")
blood_group = input("Enter Blood Group: ")
ldd = input("Enter Last Date of Donation (YYYY-MM-DD): ")
name = input("Enter Name: ")
dob = input("Enter Date of Birth (YYYY-MM-DD): ")
address = input("Enter Address: ")
district = input("Enter District: ")
state = input("Enter State: ")
country = input("Enter Country: ")
mobile1 = input("Enter Mobile Number 1: ")
mobile2 = input("Enter Mobile Number 2: ")
email = input("Enter Email: ")
add_donor(aadhaar, blood_group, ldd, name, dob, address, district,
state, country, mobile1, mobile2, email)
print("Donor added successfully.")
elif choice == 2:
blood_group = input("Enter Blood Group to search: ")
donors = search_donor_by_blood_group(blood_group)
if donors:
for donor in donors:
print(donor)
else:
print("No donors found with the specified blood group.")
elif choice == 3:
aadhaar = input("Enter Aadhaar Number to modify: ")
new_address = input("Enter New Address: ")
new_mobile1 = input("Enter New Mobile Number 1: ")
new
# Problem/Program Number: 24 Date: 09-06-2024
def create_account_table():
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS BankAccounts (
AccNo VARCHAR(20) PRIMARY KEY,
CName VARCHAR(255),
AadhaarNo VARCHAR(12),
PhoneNo VARCHAR(15),
BalanceAmt FLOAT
)
""")
conn.close()
def open_account(acc_no, cname, aadhaar_no, phone_no, balance_amt):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("""
INSERT INTO BankAccounts (AccNo, CName, AadhaarNo, PhoneNo,
BalanceAmt)
VALUES (%s, %s, %s, %s, %s)
""", (acc_no, cname, aadhaar_no, phone_no, balance_amt))
conn.commit()
conn.close()
def deposit_money(acc_no, amount):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("UPDATE BankAccounts SET BalanceAmt = BalanceAmt + %s
WHERE AccNo = %s", (amount, acc_no))
conn.commit()
conn.close()
def withdraw_money(acc_no, amount):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("SELECT BalanceAmt FROM BankAccounts WHERE AccNo =
%s", (acc_no,))
balance = cursor.fetchone()[0]
if balance >= amount:
cursor.execute("UPDATE BankAccounts SET BalanceAmt = BalanceAmt - %s
WHERE AccNo = %s", (amount, acc_no))
conn.commit()
print("Withdrawal successful.")
else:
print("Insufficient funds.")
conn.close()
def bank_menu():
while True:
print("\nBank Account Management Menu")
print("1. Open a New Account")
print("2. Deposit Money")
print("3. Withdraw Money")
print("4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
acc_no = input("Enter Account Number: ")
cname = input("Enter Customer Name: ")
aadhaar_no = input("Enter Aadhaar Number: ")
phone_no = input("Enter Phone Number: ")
balance_amt = float(input("Enter Initial Deposit Amount: "))
open_account(acc_no, cname, aadhaar_no, phone_no, balance_amt)
print("Account opened successfully.")
elif choice == 2:
acc_no = input("Enter Account Number: ")
amount = float(input("Enter Amount to Deposit: "))
deposit_money(acc_no, amount)
print("Deposit successful.")
elif choice == 3:
acc_no = input("Enter Account Number: ")
amount = float(input("Enter Amount to Withdraw: "))
withdraw_money(acc_no, amount)
elif choice == 4:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

# Run the menu


bank_menu()

# Problem/Program Number: 24 Date: 09-06-2024

def create_mcq_table():
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS MCQQuiz (
QID INT AUTO_INCREMENT PRIMARY KEY,
Question TEXT,
OptionA VARCHAR(255),
OptionB VARCHAR(255),
OptionC VARCHAR(255),
OptionD VARCHAR(255),
Answer CHAR(1)
)
""")
conn.close()
def add_question(question, option_a, option_b, option_c, option_d, answer):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("""
INSERT INTO MCQQuiz (Question, OptionA, OptionB, OptionC, OptionD,
Answer)
VALUES (%s, %s, %s, %s, %s, %s)
""", (question, option_a, option_b, option_c, option_d, answer))
conn.commit()
conn.close()
def modify_question(qid, new_question, new_option_a, new_option_b,
new_option_c, new_option_d, new_answer):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("""
UPDATE MCQQuiz SET Question=%s, OptionA=%s, OptionB=%s, OptionC=
%s, OptionD=%s, Answer=%s
WHERE QID=%s
""", (new_question, new_option_a, new_option_b, new_option_c,
new_option_d, new_answer, qid))
conn.commit()
conn.close()
def remove_question(qid):
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("DELETE FROM MCQQuiz WHERE QID=%s", (qid,))
conn.commit()
conn.close()
def play_quiz():
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = conn.cursor()
cursor.execute("SELECT * FROM MCQQuiz")
questions = cursor.fetchall()
score = 0

for question in questions:


print(f"\nQuestion {question[0]}: {question[1]}")
print(f"A) {question[2]}")
print(f"B) {question[3]}")
print(f"C) {question[4]}")
print(f"D) {question[5]}")
answer = input("Your answer: ").strip().upper()

if answer == question[6]:
score += 1

print(f"\nYour final score is {score}/{len(questions)}")


conn.close()
def mcq_menu():
while True:
print("\nMCQ Quiz Menu")
print("1. Create Quiz Table & Add Questions")
print("2. Modify Question")
print("3. Remove Question")
print("4. Play Quiz")
print("5. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:
create_mcq_table()
print("Table created successfully.")
question = input("Enter the Question: ")
option_a = input("Enter Option A: ")
option_b = input("Enter Option B: ")
option_c = input("Enter Option C: ")
option_d = input("Enter Option D: ")
answer = input("Enter Correct Answer (A/B/C/D): ").upper()
add_question(question, option_a, option_b, option_c, option_d, answer)
print("Question added successfully.")
elif choice == 2:
qid = int(input("Enter Question ID to modify: "))
new_question = input("Enter the new Question: ")
new_option_a = input("Enter new Option A: ")
new_option_b = input("Enter new Option B: ")
new_option_c = input("Enter new Option C: ")
new_option_d = input("Enter new Option D: ")
new_answer = input("Enter Correct Answer (A/B/C/D): ").upper()
modify_question(qid, new_question, new_option_a, new_option_b,
new_option_c, new_option_d, new_answer)
print("Question modified successfully.")
elif choice == 3:
qid = int(input("Enter Question ID to remove: "))
remove_question(qid)
print("Question removed successfully.")
elif choice == 4:
play_quiz()
elif choice == 5:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

# Run the menu


mcq_menu()

# Problem/Program Number: 25 Date: 09-06-2024


1. Number Sequencing Game.
import random

def number_sequencing_game():
print("Welcome to the Number Sequencing Game!")
length = int(input("Enter the length of the sequence (e.g., 3): "))
max_number = int(input("Enter the maximum number in the sequence (e.g.,
9): "))

# Generate a random sequence


sequence = [random.randint(0, max_number) for _ in range(length)]

print("\nTry to guess the sequence.")


for i in range(length):
guess = int(input(f"Enter your guess for position {i + 1}: "))
if guess == sequence[i]:
print("Correct!")
else:
print(f"Wrong! The correct number was {sequence[i]}")

print("\nThe correct sequence was:", sequence)


print("Game Over!")

number_sequencing_game()

# Problem/Program Number: 25 Date: 09-06-2024


2. Dices Game.
import random

def two_dices_game():
print("Welcome to the 2 Dices Game!")

# Roll two dice


dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
total = dice1 + dice2

guess = int(input("Guess the sum of the two dice: "))

if guess == total:
print(f"Correct! The dice rolled {dice1} and {dice2}, with a total of
{total}.")
else:
print(f"Wrong! The dice rolled {dice1} and {dice2}, with a total of {total}.")

print("Game Over!")

two_dices_game()

Rest of the problems:


Create your own module DATAANALYSIS by defining the following functions: i)
Define a Function to return Length of ARR = Len(ARR) ii) Define a Function to
return Min of ARR = Min(ARR) iii) Define a Function to return Max of ARR =
Max(ARR) iv) Define a Function to return Range of ARR = Range(ARR) v) Define a
Function to return sorted List of ARR = Sort(ARR) vi) Define a Function to return
Mean of ARR = Mean(L) vii) Define a Function to return Median of ARR =
Median(ARR) viii) Define a Function to return Dictionary
FT={0:3,1:2,2:3,,,,,,,5:1} of ARR ix) Define a Function to return Mode of ARR =
Mode(ARR) x) Define a function to return Mean deviation about M for ARR =
MDM(ARR,M) xi) Define a function to return Mean deviation about Mean for ARR
= MDMean(ARR) xii) Define a function to return Mean deviation about Median for
ARR = MDMedian(ARR) xiii) Define a function to return Mean deviation about
Mode for ARR = MDMode(ARR) xiv) Define a Function to return Variance of ARR =
Var(ARR) xv) Define a Function to return SD of ARR = SD(ARR) Write a python
program to import your own module and check all your functions for a List (and
also for a Tuple) DICE having 10 random numbers between 1 to 6 (both inclusive)

# dataanalysis.py

import math
from collections import Counter

def Len(arr):
return len(arr)

def Min(arr):
return min(arr)

def Max(arr):
return max(arr)

def Range(arr):
return Max(arr) - Min(arr)

def Sort(arr):
return sorted(arr)

def Mean(arr):
return sum(arr) / Len(arr)

def Median(arr):
n = Len(arr)
sorted_arr = Sort(arr)
mid = n // 2
if n % 2 == 0:
return (sorted_arr[mid - 1] + sorted_arr[mid]) / 2
else:
return sorted_arr[mid]

def FrequencyTable(arr):
return dict(Counter(arr))

def Mode(arr):
freq_table = FrequencyTable(arr)
max_count = max(freq_table.values())
mode = [key for key, value in freq_table.items() if value == max_count]
return mode[0] if len(mode) == 1 else mode

def MeanDeviation(arr, M):


return sum(abs(x - M) for x in arr) / Len(arr)

def MDMean(arr):
return MeanDeviation(arr, Mean(arr))

def MDMedian(arr):
return MeanDeviation(arr, Median(arr))

def MDMode(arr):
return MeanDeviation(arr, Mode(arr))

def Variance(arr):
mean = Mean(arr)
return sum((x - mean) ** 2 for x in arr) / Len(arr)

def SD(arr):
return math.sqrt(Variance(arr))
import random
import dataanalysis as da

# Generate a list of 10 random numbers between 1 and 6


DICE = [random.randint(1, 6) for _ in range(10)]
DICE_tuple = tuple(DICE)

print("List DICE:", DICE)


print("Tuple DICE:", DICE_tuple)

# Test all the functions from the dataanalysis module

print("Length of DICE:", da.Len(DICE))


print("Minimum of DICE:", da.Min(DICE))
print("Maximum of DICE:", da.Max(DICE))
print("Range of DICE:", da.Range(DICE))
print("Sorted DICE:", da.Sort(DICE))
print("Mean of DICE:", da.Mean(DICE))
print("Median of DICE:", da.Median(DICE))
print("Frequency Table of DICE:", da.FrequencyTable(DICE))
print("Mode of DICE:", da.Mode(DICE))
print("Mean Deviation about Mean of DICE:", da.MDMean(DICE))
print("Mean Deviation about Median of DICE:", da.MDMedian(DICE))
print("Mean Deviation about Mode of DICE:", da.MDMode(DICE))
print("Variance of DICE:", da.Variance(DICE))
print("Standard Deviation of DICE:", da.SD(DICE))

# Repeat for the tuple


print("\nTesting with Tuple DICE:")
print("Length of DICE:", da.Len(DICE_tuple))
print("Minimum of DICE:", da.Min(DICE_tuple))
print("Maximum of DICE:", da.Max(DICE_tuple))
print("Range of DICE:", da.Range(DICE_tuple))
print("Sorted DICE:", da.Sort(DICE_tuple))
print("Mean of DICE:", da.Mean(DICE_tuple))
print("Median of DICE:", da.Median(DICE_tuple))
print("Frequency Table of DICE:", da.FrequencyTable(DICE_tuple))
print("Mode of DICE:", da.Mode(DICE_tuple))
print("Mean Deviation about Mean of DICE:", da.MDMean(DICE_tuple))
print("Mean Deviation about Median of DICE:", da.MDMedian(DICE_tuple))
print("Mean Deviation about Mode of DICE:", da.MDMode(DICE_tuple))
print("Variance of DICE:", da.Variance(DICE_tuple))
print("Standard Deviation of DICE:", da.SD(DICE_tuple))

You might also like