SLC S21 Week3 || Mastering Records and Record Arrays with Python

Hello everyone! I hope you will be good. Today I am here to participate in the contest of @kouba01 about Mastering Records and Record Arrays with Python. It is really an interesting and knowledgeable contest. There is a lot to explore. If you want to join then:



Join Here: SLC S21 Week3 || Mastering Records and Record Arrays with Python




Creating Dynamic Interfaces with Python and Qt5 (2).png

Designed with Canva

Advanced Employee Records Management

Develop a Python program to manage employee records using dataclass. The program should support adding, updating, and displaying employee information, along with calculating average performance scores and identifying top performers.


image.png
image.png
image.png
image.png
image.png
image.png

It is the complete python program to manage the records of the employee using dataclass. The explanation of the code is given below:


image.png

from dataclasses import dataclass, field: Imports the dataclass decorator and field function from Python's dataclasses module. The dataclass decorator simplifies creating classes that store data, while field helps specify default values.
from typing import List, Optional: Imports List and Optional from the typing module, enabling type annotations for lists and optionally provided values.


image.png

@dataclass: Decorates the Employee class, allowing it to automatically generate common methods like __init__ and __repr__.
class Employee: Defines a class named Employee to represent employee data.
id: int: Specifies that each employee has an integer id.
name: str: Specifies a name field for the employee's name.
position: str: Specifies a position field for the employee's job title.
salary: float: Specifies a salary field as a floating-point number.
performance_scores: List[float] = field(default_factory=list): Defines performance_scores as a list of floats, with default_factory=list initializing it as an empty list if not specified.


image.png

def calculate_average_score: Defines a function that calculates the average score for an employee.
if employee.performance_scores:: Checks if the employee has any performance scores.
return sum(employee.performance_scores) / len(employee.performance_scores): Calculates and returns the average by dividing the sum by the count of scores.
return 0.0: If there are no scores, it returns 0.0 as the average.


image.png

def add_employee: Defines a function to add a new employee to the list of employees.
emp_id = int(input("Enter Employee ID: ")): Prompts the user to input an employee ID and converts it to an integer.
if any(emp.id == emp_id for emp in employees):: Checks if the provided ID already exists in the employee list.
print and return: If the ID exists, prints a message and exits the function.
Prompts the user to input values for name, position, salary, and performance_scores.
employees.append(...): Creates an Employee instance with provided details and adds it to the list.
print: Confirms successful addition.


image.png

def update_employee: Defines a function to update an employee’s details.
emp_id = int(input("Enter Employee ID to update: ")): Prompts for the employee’s ID to update.
for employee in employees:: Iterates over the list of employees.
if employee.id == emp_id:: Checks if the current employee’s ID matches the input.
User input lines: Prompts for each attribute, allowing the user to press Enter to skip updating.
Attribute updates: Updates the employee’s attributes if input is provided.
print and return: Confirms success and exits. If no match is found, a message indicates this.


image.png

display_employees: Lists all employees with average scores.
for emp in employees:
: Loops through employees, calculates, and displays each employee’s details.


image.png

display_average_score_for_employee: Finds and displays a specific employee’s average score based on their ID.


image.png

top_performers: Identifies and lists employees with average scores at or above a given threshold.


image.png

main: Provides an interactive menu for managing employee records, with a loop for handling user input until the program exits. Each choice calls the respective function.



Comprehensive Student Grades Analysis

Utilize NumPy's structured arrays to store and analyze student grades, including calculating averages, identifying top students, and analyzing subject-wise performance.


image.png
image.png
image.png
image.png

Importing NumPy


image.png

This imports the NumPy library, which provides functions to create and manipulate arrays efficiently.

Structured Array


image.png

This student_dtype variable defines the structure (data type) for each student record, with:

  • student_id as a 4-byte integer (i4)
  • name as a 20-character Unicode string (U20)
  • Each grade field (math_grade, science_grade, etc.) as a 4-byte float (f4).

Initialize Sample Data


image.png

This students_data array holds sample student data with IDs, names, and grades in four subjects. The structured array format allows each entry to be accessed by name (e.g., student['math_grade']).

Calculate Average Grades for Each Student


image.png

This function iterates over each student, calculates the average of their grades, and stores it in a dictionary (averages) with the student’s name as the key.

Identify Students Above a Threshold


image.png

This function identifies students whose average grade is above a specified threshold. It collects their names in a list and returns it.

Determine the Top Student by Average Grade


image.png

This function finds the student with the highest average grade:

  • It initializes top_name as None and top_avg as -1 to ensure any valid average grade will be higher.
  • For each student, it calculates the average grade.
  • If the average grade is higher than the current top_avg, it updates top_avg and top_name with the current student's data.
  • Finally, it returns the name and average grade of the top student.

Calculate Average Grades for Each Subject


image.png

This function calculates the average grade for each subject across all students:

  • It iterates over each subject, computes the mean for that subject, and stores it in a dictionary.
  • This dictionary, averages, maps each subject name to its average grade across all students.

Identify Subjects Below a Passing Grade


image.png

This function finds subjects with average grades below a specified passing_grade:

  • It iterates through each subject, calculates its average grade, and checks if it is below passing_grade.
  • If a subject’s average is below this threshold, it adds the subject and its average grade to the below_passing dictionary.
  • This dictionary is then returned, showing which subjects need improvement.

Display Results


image.png

This final section prints the results of each analysis:

  • Average Grades per Student: Calls calculate_student_averages and prints each student’s average grade.
  • Students with Average Grades Above 75: Calls students_above_threshold to list students with averages above 75.
  • Top Student: Calls top_student to display the student with the highest average.
  • Average Grade for Each Subject: Calls subject_averages to show average grades by subject.
  • Subjects Below Passing Grade: Calls subjects_below_passing and displays subjects that have an average grade below 60. If no subject falls below this threshold, it prints "None".

This code structure efficiently organizes student data and performs multiple types of analyses, making it easy to expand or adjust thresholds and criteria as needed.


image.png

This is the output of the program after compiling all the code.



Enhanced Inventory Management System

Develop an inventory management system using namedtuple to track products, including functionalities for low stock alerts and identifying high-value products.


image.png
image.png
image.png
image.png

Here’s a complete breakdown of the inventory management code while explaining each function and part of the code in detail:

Imports and Named Tuple Definition


image.png

  • from collections import namedtuple: Imports namedtuple from Python’s collections module, allowing us to create a simple class-like structure for storing related data.
  • from typing import List: Imports List from typing to annotate the type of list we use in functions.


image.png

  • Defines a Product named tuple with fields: product_id, name, quantity, price, and category. Each instance of Product will store these details for a specific item in the inventory.

Function Definitions

Each function manages a specific part of the inventory system, allowing for modular operations that can be accessed individually through the main interactive shell.

Function: add_product


image.png

  • Purpose: Allows the user to add a new product to the inventory list.
  • Steps:
    • Prompts for product details (product_id, name, quantity, price, category) and converts input to the appropriate data type.
    • Creates a new Product instance and appends it to the products list.
    • Handles ValueError exceptions to ensure valid data types (e.g., integers for IDs and quantities, floats for prices).

Function: update_product_quantity


image.png

  • Purpose: Updates the quantity of a specified product.
  • Steps:
    • Prompts for the product_id and new quantity.
    • Searches for the product by product_id in the products list.
    • If found, updates the product’s quantity using _replace() (a method for namedtuple instances to return a modified copy).
    • If not found, prints "Product not found." Handles ValueError exceptions for input.

Function: calculate_total_inventory_value


image.png

  • Purpose: Calculates and displays the total monetary value of the inventory.
  • Steps:
    • Multiplies each product’s quantity by its price and sums the values for all products.
    • Prints the total inventory value, formatted to two decimal places.

Function: generate_low_stock_alerts


image.png

  • Purpose: Provides alerts for products that have a quantity below a specified threshold.
  • Steps:
    • Prompts for a threshold and iterates over products.
    • If a product’s quantity is below the threshold, it is listed as low stock.
    • Catches ValueError exceptions for input validation.

Function: highest_value_product


image.png

  • Purpose: Finds and displays the product with the highest total value (quantity × price).
  • Steps:
    • If the products list is empty, it informs the user and returns.
    • Uses max() with a lambda function (p.quantity * p.price) to find the product with the highest value.

Function: summarize_inventory_by_category


image.png

  • Purpose: Calculates and displays the total value of products grouped by category.
  • Steps:
    • Iterates over products, accumulating each category’s total value in category_totals.
    • Prints each category with its total value, formatted to two decimal places.

Main Interactive Shell


image.png
image.png

  • Purpose: Provides a menu-driven interface to perform different inventory operations.
  • Steps:
    • Initializes an empty products list.
    • Displays the menu and prompts the user to choose an option.
    • Based on the choice, calls the corresponding function to add a product, update a quantity, calculate total value, generate low stock alerts, find the highest value product, summarize by category, or exit the program.



Advanced Customer Orders Processing

Create a program to process customer orders using NumPy's structured arrays, including functionalities for calculating order totals, identifying large orders, and analyzing customer purchasing patterns.


image.png
image.png
image.png
image.png

Here is the complete breakdown of the python program to process the customer orders using NumPy's structured arrays.

Imports


image.png

  • numpy (imported as np): This library is used for numerical operations, especially with arrays, and is used here for structured arrays and numerical calculations.
  • defaultdict from collections: This is a dictionary subclass that provides a default value for non-existent keys, useful here for grouping products by date.

Define the Structured Array for Orders


image.png

  • This defines the structure of each order record, specifying the fields and data types:
    • order_id: integer (4 bytes, or i4).
    • customer_name: Unicode string with a max length of 20 characters (U20).
    • product: Unicode string up to 20 characters.
    • quantity: integer for the quantity of each product.
    • price_per_unit: float (4 bytes).
    • order_date: Unicode string with a max length of 10 characters (format: 'YYYY-MM-DD').

Sample Data of Customer Orders


image.png

  • This orders_data array uses the order_dtype structure to store each order as a record. It contains sample orders with details such as order_id, customer_name, product, quantity, price_per_unit, and order_date.

Functions

  1. Calculate Total Price for Each Order


    image.png

    • This function computes the total cost per order by multiplying the quantity and price_per_unit for each order in the array.
  2. Identify Large Orders (Above a Threshold)


    image.png

    • This function identifies orders with a total value greater than a specified threshold (default of $200). It calculates totals using calculate_order_totals and then filters orders where the total exceeds the threshold, returning the order_ids.
  3. Determine the Customer with the Highest Total Spending


    image.png

    • This function first creates a dictionary customer_totals to track total spending per customer. For each unique customer, it calculates the sum of order totals where the customer_name matches. The customer with the highest total spending is then identified and returned.
  4. Analyze Total Orders and Spending Per Customer


    image.png

    • This function provides a summary of total orders and spending per customer by grouping each customer's orders, calculating their total spending, and counting their orders. The result is stored in analysis, with each customer's name as a key.
  5. Identify Products Ordered Together on the Same Date


    image.png

    • This function groups products by their order_date using a defaultdict to build a list of products ordered on each date.
    • If more than one product was ordered on the same date, the date and the products are added to the frequently_ordered dictionary. This dictionary is returned, showing which products were ordered together on specific dates.

Display Results


image.png

  • This loop displays the total price for each order by iterating through orders_data and calculated totals.


image.png

  • This displays the order_id of each order with a total price above $200.


image.png

  • This section displays the customer with the highest spending.


image.png

  • This outputs a summary of the number of orders and total spending per customer.


image.png

  • This displays the products ordered together on each date with multiple items, formatted to show the date and products ordered.


image.png
image.png

The program provides a complete system for tracking and analyzing orders, including identifying high value customers, orders exceeding a price threshold and products frequently ordered together. It uses numpy for array management and collections.defaultdict for grouping making it both efficient and adaptable.



In-Depth Weather Data Analysis

Analyze weather data using dataclass and NumPy, including functionalities for calculating averages, identifying trends, and detecting anomalies.


image.png
image.png
image.png
image.png

Here’s a complete breakdown of the program to analyze weather data using dataclass and NumPy.

Imports and Setup


image.png

  • numpy: Used for numerical operations, particularly calculating averages, maximums, and summing lists.
  • dataclasses.dataclass: Used to create a WeatherRecord class that holds structured weather data.
  • typing.List: Specifies a list of WeatherRecord instances.

WeatherRecord Dataclass


image.png

  • WeatherRecord: This is a dataclass that stores weather data for each day, including the date, temperature, humidity, precipitation, and wind speed.

Sample Data


image.png

  • weather_data: A list of WeatherRecord instances representing sample weather data.

Helper Functions

calculate_averages


image.png

  • This function calculates:
    • Average temperature
    • Maximum humidity
    • Total precipitation
    • Average wind speed
  • It uses numpy functions like np.mean, np.max, and np.sum.

identify_temperature_threshold


image.png

  • This function accepts a temp_threshold, identifies days where the temperature is above or below it, and prints these dates.

detect_trends


image.png

  • This function checks if temperature and precipitation values are increasing, decreasing, or stable based on the first and last values in the dataset.

detect_anomalies


image.png

  • This function detects temperature spikes (changes greater than 5°C between consecutive days) and lists these as anomalies.

main_menu Function


image.png

  • The main menu prompts the user with five options:

    1. Calculate averages
    2. Identify temperature thresholds
    3. Detect trends
    4. Detect temperature anomalies
    5. Exit
  • Depending on the choice, the relevant function is called, and the user can view or analyze the weather data interactively.

Running the Program


image.png

  • main_menu runs as the program’s entry point, enabling interactive analysis of weather data based on the provided options.

This code provides an effective way to manage and analyze weather records using structured data and simple numerical computations.



I have explained and written all the programs step by step by gradually explaining each part.



I would like to invite @heriadi, @chant and @suboohi to join this contest.

Sort:  
Loading...

Congratulations, your post has been upvoted by @scilwa, which is a curating account for @R2cornell's Discord Community. We can also be found on our hive community & peakd as well as on my Discord Server

Manually curated by @ abiga554
r2cornell_curation_banner.png

Felicitaciones, su publication ha sido votado por @scilwa. También puedo ser encontrado en nuestra comunidad de colmena y Peakd así como en mi servidor de discordia

Coin Marketplace

STEEM 0.21
TRX 0.20
JST 0.034
BTC 98085.38
ETH 3350.61
USDT 1.00
SBD 3.03