Programming Notes 3
Programming Notes 3
pyplot as plt
which has the columns productCategory (the category of the product, e.g. Electronics,
Question Two [10 marks]
Clothing), storeName (the name of the store, e.g. “JB Hi-Fi”), saleAmount (the sale amount
in Australian Dollars), and saleDate (the date of the sale); a. Using Python code, in the most efficient manner possible as taught in the "Programming for
Business" unit, write the following functions:
import pandas as pd
i. [3 marks] A function named random_selector that takes any number of numerical
sales_df = pd.read_csv('sales_data.csv')
arguments. The function should generate a random whole number between -100 and 100
ii. [1 mark] Convert the columns in the DataFrame from Question 1ai that contain non-text data (inclusive) and return a list of all arguments that are greater than or equal to that random
into the most appropriate data types for the data, assuming that all data is in the correct number.
format;
import random
sales_df['saleAmount'] = sales_df['saleAmount'].astype(float)
def random_selector(*args):
sales_df['saleDate'] = pd.to_datetime(sales_df['saleDate'])
rand_num = random.randint(-100, 100)
iii. [1 mark] Calculate and display the total sales amount for each product category within the the_list = list(filter(lambda x: x > rand_num, args))
return(the_list)
DataFrame referred to in Question 1aii, alongside the highest sales amount for each store;
ii. [3 marks] A function named format_date that takes a single datetime object named dt_obj
print(sales_df.groupby('productCategory')['saleAmount'].sum())
as an argument and outputs the date in a format matching "November 15, 2023".
print(sales_df.groupby('storeName')['saleAmount'].max())
def format_date(dt_obj):
iv. [1 mark] Display the data within the DataFrame referred to in Question 1aii for sales that are return dt_obj.strftime('%B %d, %Y')
greater than $500.00 and occurred after the first day of this current month (this value can be iii. [4 marks] A function named compare_tuples that accepts two arguments named tuple_a
fixed and does not need to be calculated); and tuple_b (both tuples of integer values). The function should return two sets: the common
values between the two tuples and the unique values between of the two tuples.
print(sales_df[(sales_df['saleAmount'] > 200) & (sales_df['saleDate'] >'2024-10-01')])
v. [1 mark] Write the required code to visualise the total sales by productCategory calculated def compare_tuples(tuple_a, tuple_b):
common_values = tuple(set(tuple_a) & set(tuple_b))
in Question 1aiii as a bar chart, ensuring appropriate labels and formatting are applied to the unique_values = tuple(set(tuple_a) ^ set(tuple_b))
plot. return common_values, unique_values
Page 1 of 5 Page 2 of 5
Question Three [15 marks] for year in [2021, 2022, 2023]:
products_in_year = [row for row in inventory_data if row['stockDate'].year == year]
a. You have been provided with a CSV file named inventory_data.csv containing the following if products_in_year:
avg_margin = sum(row['profitMargin'] for row in products_in_year) /
columns: itemName (the name of the product), itemCostPrice (the cost to produce the product), len(products_in_year)
itemSalePrice (the price the product is sold for), and stockDate (the date when the product print(f"Average profit margin for {year}: {avg_margin:.2f}")
ii. [2 marks] Calculate the profit margin (difference between the sale price and cost price, def get_shiftID(self):
assuming sale price is always larger) for each product and add it to each dictionary. return(self.shiftID)
iii. [3 marks] Identify and display the itemName of the product with the highest and lowest profit def get_shiftDuration(self):
return(self.shiftDuration)
margin.
def set_shiftDuration(self, shiftDuration):
max_margin_product = max(inventory_data, key=lambda x: x['profitMargin']) self.shiftDuration = shiftDuration
min_margin_product = min(inventory_data, key=lambda x: x['profitMargin'])
def get_shiftType(self):
print("Product with highest profit margin:", max_margin_product['itemName']) return(self.shiftType)
print("Product with lowest profit margin:", min_margin_product['itemName'])
def set_shiftType(self, shiftType):
iv. [3 marks] Calculate and report the average profit margin for products first stocked in each of self.shiftType = shiftType
the years 2021, 2022, and 2023.
def __str__(self):
Page 3 of 5 Page 4 of 5
return(f"Shift ID: {self.shiftID}, Duration: {self.shiftDuration}, Shift Type:
{self.shiftType}")
class StaffMember():
""" Information about a service. """
def __init__(self, staffName, shift_list):
self.staffName = staffName
self.shift_list = shift_list
def get_staffName(self):
return(self.staffName)
def get_shift_list(self):
return(self.shift_list)
def number_of_shift_list(self):
return(len(self.shift_list))
def __str__(self):
return(f"Staff: {self.staffName}, no. of shift: {len(self.shift_list)}")
Page 5 of 5