Answer:
Problem - 1
"""
Count Characters in a String
=================================
Author: Udit Kumar Chatterjee
Email: quantumudit@gmail.com
=================================
This script defines a function, count_chars, which counts the frequency of each character
in a given input string and returns a dictionary with characters as keys and their
respective counts as values.
"""
def count_chars(text: str) -> dict:
"""
Count the frequency of each character in the input text and return a dictionary
with characters as keys and their respective counts as values.
Args:
text (str): The input text to analyze.
Returns:
dict: A dictionary where keys are characters and values are their counts.
"""
# Convert the input text to a list of characters
char_list = [char for char in text]
char_count = {}
for char in char_list:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
return char_count
if __name__ == "__main__":
WORD = "banana"
result = count_chars(text=WORD)
print(result)
Problem - 2
"""
Filter Students Older Than a Specified Age Limit
================================================
Author: Udit Kumar Chatterjee
Email: quantumudit@gmail.com
================================================
This script defines a function, filter_students_older_than_limit, which filters a list
of student data to include only students less than a specified age limit.
"""
def filter_students_older_than_limit(student_data: list, age_limit: int):
"""
Filters a list of student data to include only students older than a specified age limit.
Args:
student_data (list): A list of tuples or lists containing student information.
Each student data item should have at least three elements:
(name: str, age: int, other_info: any)
age_limit (int): The minimum age for students to be included in the filtered list.
Returns:
list: A filtered list containing student data for students older than the age limit.
Each item in the filtered list has the same format as the input data.
Raises:
ValueError: If the data format is not a tuple or a list with at least three elements,
or if the age is not an integer.
"""
filtered_data = []
for student_info in student_data:
if isinstance(student_info, (tuple, list)) and len(student_info) == 3:
_, age, _ = student_info
if isinstance(age, int):
if age < age_limit:
filtered_data.append(student_info)
else:
pass
else:
raise ValueError(
f"Student age should be an integer value: {student_info}")
else:
raise ValueError(
f"The data format must be a tuple or a list with three elements: {student_info}")
return filtered_data
if __name__ == '__main__':
student_dataset = [
("John", 13, "Grade 10"),
("Emily", 14, "Grade 9"),
("Sam", 16, "Grade 11")
]
result = filter_students_older_than_limit(student_dataset, 15)
print(result)
Problem - 3
"""
Find Product with Highest Sales
=================================
Author: Udit Kumar Chatterjee
Email: quantumudit@gmail.com
=================================
This script defines a function, find_product_with_highest_sales,
which identifies the product with the highest sales
based on the input sales transaction data.
"""
def find_product_with_highest_sales(data: list):
"""
Find the product with the highest sales based on the input data.
Args:
data (list): A list of tuples or lists containing sales transaction data.
Each data item should have three elements, i.e., transaction ID,
product ID and sales price
Returns:
tuple: A tuple containing the product ID and the total sales amount
of the product with the highest sales.
Raises:
ValueError: If the data format is not a tuple or a list with three elements,
or if the sales price is not a numerical value.
"""
product_sales = {}
for sales_record in data:
if isinstance(sales_record, (tuple, list)) and len(sales_record) == 3:
_, product_id, sales_price = sales_record
if isinstance(sales_price, (int, float)):
if product_id in product_sales:
product_sales[product_id] += sales_price
else:
product_sales[product_id] = sales_price
else:
raise ValueError(
f"Product sales price must be a numerical value: {sales_record}")
else:
raise ValueError(
f"The data format must be a tuple or a list with three elements: {sales_record}")
# Find the product with the highest sales
top_product_id = max(product_sales, key=lambda k: product_sales[k])
top_product_sales = product_sales[top_product_id]
return top_product_id, top_product_sales
if __name__ == '__main__':
transactions = [
(1, 101, 15.0),
(2, 102, 20.0),
(3, 101, 15.0),
(4, 103, 10.0),
(5, 102, 20.0),
(6, 101, 15.0),
(7, 103, 10.0),
(8, 102, 20.0),
(9, 103, 10.0)
]
result = find_product_with_highest_sales(data=transactions)
print(
f"The product ID {result[0]} has the highest sales. The sales amount is ${result[1]:,.1f}")
Bonus Challenge
"""
Circle Class
=============================
Author: Udit Kumar Chatterjee
Email: quantumudit@gmail.com
=============================
This script defines a Python class, Circle, for representing circles. The class provides methods for
manipulating and calculating properties of circles.
"""
class Circle:
"""Class representing a circle"""
def __init__(self, radius: float):
"""
Initialize a Circle object with a given radius.
Args:
radius (float): The radius of the circle.
"""
self.radius = radius
self.pi = 3.14
def get_radius(self) -> float:
"""
Get the current radius of the circle.
Returns:
float: The radius of the circle.
"""
return self.radius
def set_radius(self, new_radius: float):
"""
Set the radius of the circle to a new value.
Args:
new_radius (float): The new radius value to set.
"""
self.radius = new_radius
def calculate_area(self) -> float:
"""
Calculate the area of the circle.
Returns:
float: The area of the circle.
"""
return self.pi * (self.radius ** 2)
def calculate_circumference(self) -> float:
"""
Calculate the circumference of the circle.
Returns:
float: The circumference of the circle.
"""
return 2 * self.pi * self.radius
if __name__ == '__main__':
cir = Circle(radius=5)
print(f"The radius of the circle is: {cir.get_radius()}")
cir.set_radius(new_radius=10)
print(f"The updated radius of the circle is: {cir.get_radius()}")
calc_area = round(cir.calculate_area(), 2)
print(f"The area of the circle is: {calc_area:.2f}")
calc_peri = round(cir.calculate_circumference(), 2)
print(f"The circumference of the circle is: {calc_peri:.2f}")