CS practical file non cover
CS practical file non cover
"""
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.
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='')
# Sample Output:
# 1
# 212
# 32123
# 4321234
# 543212345
"""
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.
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)
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()
# 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 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.
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:")
# 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 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.
# Sample Output:
# Enter the first number (M): 15
# Enter the second number (N): 28
# 15 and 28 are co-prime.
"""
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.
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
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.")
# Sample Output:
# Enter a number (M): 28
# 28 is a perfect number.
"""
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.
"""
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
return sum_factors
# Sample Output:
# Enter the first number (A): 220
# Enter the second number (B): 284
# 220 and 284 are amicable numbers.
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)}")
# 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
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)}")
# 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 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.
"""
# User inputs
X = float(input("Enter the value of X: "))
N = int(input("Enter the value of N: "))
"""
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.
"""
"""
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.
"""
"""
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.
"""
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)
"""
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.
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])
if length % 2 != 0:
# If the word has an odd number of characters, append the last character
encoded_word.append(transformed_word[-1])
# Sample Output:
# Input: "Hello World!"
# Output: "hElLo wOrLd!"
"""
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()
"""
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.
"""
"""
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 = []
# 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)
"""
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.
"""
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)
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 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.
"""
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)
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 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.
"""
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 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.
"""
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 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.
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.")
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 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.
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.")
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 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)
"""
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 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)
"""
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 = {}
return FT
“
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()
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")
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.")
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")
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")
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.")
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
if answer == question[6]:
score += 1
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.")
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): "))
number_sequencing_game()
def two_dices_game():
print("Welcome to the 2 Dices Game!")
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()
“
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 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