Professional Documents
Culture Documents
1)Write a Python program to count the number of characters (character frequency) in a string.
You can use the following Python program to count the number of characters (character frequency) in
a string:
def count_characters(string):
char_frequency = {}
if char in char_frequency:
char_frequency[char] += 1
else:
char_frequency[char] = 1
return char_frequency
sample_string = 'google.com'
result = count_characters(sample_string)
print(result)
In this program, we define the count_characters function that takes a string as input. It initializes an
empty dictionary char_frequency to store the character frequencies.
Next, we iterate over each character in the string. If the character already exists as a key in the
char_frequency dictionary, we increment its value by 1. Otherwise, we add the character as a new
key in the dictionary with a value of 1.
Finally, we return the char_frequency dictionary, which contains the character frequencies. In the
example above, the program counts the characters in the sample string 'google.com' and produces
the expected result.
2)Write an interactive menu driven program with the following four functions:
Here's a Python program that implements an interactive menu-driven program with the requested
functions:
import shutil
def create_file():
file_name = "Nation.txt"
def display_file():
file_name = "Nation.txt"
try:
content = file.read()
print(f"Content of '{file_name}':\n{content}")
except FileNotFoundError:
def append_content():
file_name = "Nation.txt"
def make_copy():
original_file = "Nation.txt"
copy_file = "Nation_copy.txt"
try:
shutil.copyfile(original_file, copy_file)
except FileNotFoundError:
def count_occurrences():
file_name = "Nation.txt"
try:
content = file.read()
count = content.count("the")
except FileNotFoundError:
def print_menu():
print("\nMenu:")
print("q) Quit")
while True:
print_menu()
if choice == "a":
create_file()
display_file()
append_content()
make_copy()
count_occurrences()
break
else:
This program provides an interactive menu to perform various operations on a file called "Nation.txt".
You can run this program, and it will prompt you to enter your choice from the menu. Depending on
the choice you make, it will execute the corresponding function.
3) Write a function in Python to search and display details of all those students, whose stream is
“HUMANITIES” from pickled file “Student.dat”. Assuming the pickled file containing
To search and display details of students whose stream is "HUMANITIES" from a pickled file called
"Student.dat," you can use the following Python function
import pickle
def search_students_by_stream(stream):
try:
students = pickle.load(file)
if len(humanities_students) == 0:
else:
print(f"Roll: {student['Roll']}")
print(f"Name: {student['Name']}")
print(f"Stream: {student['Stream']}")
print(f"Percent: {student['Percent']}")
print()
except FileNotFoundError:
search_students_by_stream("HUMANITIES")
In this function, we open the "Student.dat" file in binary mode using the "rb" mode. We load the data
from the file using the pickle.load() function, which returns a list of dictionaries representing the
students.
We then use a list comprehension to filter out the students whose stream matches the provided
stream parameter.
If there are no students found with the specified stream, we print a corresponding message.
Otherwise, we iterate over the humanities_students list and display the details of each student,
including their roll number, name, stream, and percentage.
You can call this function with the desired stream (e.g., "HUMANITIES") to search and display the
details of the relevant students from the pickled file.
4)Write a function MULTIPLEX( ) in python to search and delete all the content in a
pickled file CINEMA.DAT, where MTYPE is matching with the value ‘Comedy’. File
To search and delete all the content in a pickled file called "CINEMA.DAT" where MTYPE matches
the value "Comedy", you can use the following Python function:
import pickle
import os
def multiplex():
try:
movies = pickle.load(file)
if len(comedy_movies) == 0:
os.remove("CINEMA.DAT")
except FileNotFoundError:
# Example usage
multiplex()
In this function, we open the "CINEMA.DAT" file in binary mode using the "rb" mode. We load the
data from the file using the pickle.load() function, which returns a list of dictionaries representing the
movies.
We then use a list comprehension to filter out the movies whose MTYPE matches the value
'Comedy'.
If there are no movies found with the specified MTYPE, we print a corresponding message.
Otherwise, we delete the content of the file using the os.remove() function, effectively deleting the file.
You can replace this line with other operations, such as truncating the file or modifying the content as
per your requirements.
You can call this function to search and delete the content from the pickled file "CINEMA.DAT" where
MTYPE matches the value 'Comedy'.
parameter and count and return number of Items by the given Company are stored in the
import struct
def CountRec(company):
count = 0
try:
while True:
if not record:
break
if decoded_company == company:
count += 1
except FileNotFoundError:
return count
def AddRecord(record_list):
try:
file.write(record)
except FileNotFoundError:
# Example usage
AddRecord(record)
We open the "Store.dat" file in binary mode using the "rb" mode.
We read the file in a loop, reading 16 bytes at a time (4 bytes for each field).
Using the struct.unpack function, we unpack the bytes into the respective fields: item_no,
item_name, record_company, and price.
We decode the record_company bytes into a string and remove any null characters ('\x00').
If the decoded company matches the provided company parameter, we increment the count.
Finally, we return the count.
You can call these functions as per your requirements, providing the company name for counting
records and the record list for adding a new record to the "Store.dat" binary file.
6)A blood bank maintains data file “Blood.dat” that contains following information for every
donor: donor name, donor date of birth, donor address, donor phone number and donor blood
Here's a complete program that performs the required operations on the "Blood.dat" data
file:import pickle
def create_file():
donor_data = []
pickle.dump(donor_data, file)
def append_record():
donor_data = pickle.load(file)
donor = {}
donor_data.append(donor)
pickle.dump(donor_data, file)
def display_records():
try:
donor_data = pickle.load(file)
if len(donor_data) == 0:
else:
print("Donor Details:")
print(f"Name: {donor['name']}")
print(f"Address: {donor['address']}")
print()
except FileNotFoundError:
def search_donor_by_blood_group(blood_group):
try:
donor_data = pickle.load(file)
found = False
if donor['blood_group'].lower() == blood_group.lower():
print("Donor Details:")
print(f"Name: {donor['name']}")
print(f"Address: {donor['address']}")
print()
found = True
if not found:
except FileNotFoundError:
def modify_donor_info():
try:
donor_data = pickle.load(file)
found = False
if donor['name'].lower() == donor_name.lower():
print(f"Name: {donor['name']}")
print(f"Address: {donor['address']}")
print()
break
if not found:
pickle.dump(donor_data, file)