Python Workout 13

Level of Difficulty:

Objective: This workout provides more practice in creating custom functions for analyzing data.

  1. Write a Python function that accepts a string as input and returns a dictionary containing the count of each character in the string. For example, given the string “banana”, the function should return {‘b’: 1, ‘a’: 3, ‘n’: 2}.

  2. Given a list of tuples representing student information like students = [(“John”, 15, “Grade 10”), (“Emily”, 14, “Grade 9”), (“Sam”, 16, “Grade 11”)], write a Python function to filter out the students who are older than 15.

  3. Let’s assume you have a list of tuples stored in the variable transactions, each representing a transaction in an e-commerce store where the first element is the transaction ID, the second element is the product ID, and the third element is the price.

Write a Python function to find the product with the highest total sales.

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), 
] 

Bonus: Object Oriented Programming

In Python, OOP allows us to encapsulate related properties and behaviors into individual objects. This challenge will involve creating a simple class and methods.

The problem is to create a Circle class that represents a circle. The circle will be initialized with a radius. The class should have the following methods:

• get_radius(): This method should return the radius of the circle.
• set_radius(new_radius): This method should set a new radius for the circle.
• calculate_area(): This method should calculate and return the area of the circle using the formula πr^2. You can use 3.14 as the approximation for π.
• calculate_circumference(): This method should calculate and return the circumference of the circle using the formula 2πr.

To test your implementation, create an instance of the circle with a radius of 5, update the radius to 10, and then calculate the area and circumference.

Simply post your code and a screenshot of your results.

Please format your Python code and blur it or place it in a hidden section.

This workout will be released on Monday May 15, 2023, and the author’s solution will be posted on Sunday May 21, 2023.

1 Like

Question 1.
Here’s my python script to count each character in a string:

Summary

count the chars in a string and store in a dictionary

def count_chars(string):
char_count = {}
for char in string:
char_count[char] = char_count.get(char, 0) + 1
return char_count

input_string = ‘This is a test!’
result = count_chars(input_string)
print(result)

Here’s the input string and function result:

Input String: “This is a crazy question!”
Function Output: {‘T’: 1, ‘h’: 1, ‘i’: 3, ‘s’: 3, ’ ': 4, ‘a’: 2, ‘c’: 1, ‘r’: 1, ‘z’: 1, ‘y’: 1, ‘q’: 1, ‘u’: 1, ‘e’: 1, ‘t’: 1, ‘o’: 1, ‘n’: 1, ‘!’: 1}

Question 2.

I had two different approaches to filtering out the students whose age was older than 15.

Solution 1. Uses a for loop and if statement

Summary

filter students older than 15

def filter_students(list, num):
student_list = list
for index, item in enumerate(list):
if item[1] > num:
print(f’{item[0]} is in {item[2]}, and is {item[1]} years old. This is older than the filter criteria of {num}, so will be removed from the list.')
del student_list[index]
return student_list

Solution 2. Uses a modified inline for loop with conditioning

Summary

filter students older than 15

def filter_students(list, num):
student_list = list

student_list = [item for index,item in enumerate(student_list) if item[1] <= num]

return student_list

Both Solutions use the same code to print the students and call the function:

students = [(‘John’, 15, ‘Grade 10’), (‘Emily’, 14, ‘Grade 9’), (‘Sam’, 16, ‘Grade 11’)]
age_filter = 15

print(f’There are {len(students)} students.‘)
print(’')
print(‘Their details are:’)

for index, item in enumerate(students):
print(f’{item[0]} is in {item[2]}, and is {item[1]} years old.')

result = filter_students(students, age_filter)
print(‘’)
print(f’The students who are {age_filter} or younger, are:')
for item in result:
print(item[0])

OUTPUT Results:

Solution 1 Output:

There are 3 students.

Their details are:
John is in Grade 10, and is 15 years old.
Emily is in Grade 9, and is 14 years old.
Sam is in Grade 11, and is 16 years old.

Sam is in Grade 11, and is 16 years old. This is older than the filter criteria of 15, so will be removed from the list.

The students who are 15 or younger, are:
John
Emily

Solution 2 Output:

There are 3 students.

Their details are:
John is in Grade 10, and is 15 years old.
Emily is in Grade 9, and is 14 years old.
Sam is in Grade 11, and is 16 years old.

The students who are 15 or younger, are:
John
Emily

Problem 1:

def count_characters(string):
    char_count = {}
    
    for char in string:
        if char in char_count:
            char_count[char] += 1
        else:
            char_count[char] = 1
    
    return char_count

Problem 2:

def filter_students(students):
    filtered_students = []

    for student in students:
        name, age, grade = student
        if age > 15:
            filtered_students.append(student)

    return filtered_students

Problem 3

def find_product_with_highest_sales(transactions):
    sales_by_product = {}

    for transaction in transactions:
        _, product_id, price = transaction
        if product_id in sales_by_product:
            sales_by_product[product_id] += price
        else:
            sales_by_product[product_id] = price

    highest_sales_product = max(sales_by_product, key=sales_by_product.get)
    return highest_sales_product

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}")