0% found this document useful (0 votes)
4 views

Programming Notes 3

Uploaded by

Duy Bui
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Programming Notes 3

Uploaded by

Duy Bui
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

import matplotlib.

pyplot as plt

BUSN5101 Mock Exam Sem 2 2024 total_sales_by_category = sales_df.groupby('productCategory')['saleAmount'].sum()


total_sales_by_category.plot(kind='bar',
Question One [5 marks] y='saleAmount',
x='productCategory',
xlabel='Product Category',
a. Utilising the pandas and matplotlib.pyplot libraries, complete the following tasks by writing
ylabel='Total Sales Amount ($)',
Python code as taught in "Programming for Business": title='Total Sales by Product Category')
i. [1 mark] Read in a CSV file named sales_data.csv into a DataFrame named sales_df, plt.show()

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

was first stocked, in YYYY-MM-DD format).


Question Four [20 marks]
Using the csv, datetime, and json modules (and any built-in Python functionality), write Python
a. You have been tasked with modelling a staff scheduling system for your organisation. Design,
code to achieve the following as taught in the "Programming for Business" unit:
using Pseudocode, the following two classes based on object-oriented programming principles
i. [7 marks] Read the CSV file into a list of dictionaries, where each dictionary represents a row as taught in the "Programming for Business" unit:
from the file, with keys corresponding to the column names and values corresponding to each i. [6 marks] A Shift class that has a shiftID, a shiftDuration (in hours), and a shiftType
row's data. Ensure the date is converted to a datetime object. (e.g. Morning, Afternoon, Night);
ii. [6 marks] A StaffMember class that contains a staffName, a list of Shift objects, and a
import csv
from datetime import datetime method named totalShifts that returns the total number of shifts a staff member has.
b. [8 marks] Implement your designs from Questions 4ai and 4aii using Python code, then create
# Reading the CSV file into a list of dictionaries
csv_file = open('inventory_data.csv', 'r') an instance of the Shift class and use it to create an instance of the StaffMember class.
csv_reader = csv.DictReader(csv_file)
inventory_data = [] class Shift():
for row in csv_reader: """ Information about staff scheduling system. """
row['itemCostPrice'] = float(row['itemCostPrice'])
row['itemSalePrice'] = float(row['itemSalePrice']) def __init__(self, shiftID, shiftDuration, shiftType):
row['stockDate'] = datetime.strptime(row['stockDate'], '%Y-%m-%d') self.shiftID = shiftID
inventory_data.append(row) self.shiftDuration = float(shiftDuration)
csv_file.close() self.shiftType = shiftType

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)

def set_shiftID(self, shiftID):


for row in inventory_data:
self.shiftID = shiftID
row['profitMargin'] = row['itemSalePrice'] - row['itemCostPrice']

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 set_staffName(self, staffName):


self.staffName = staffName

def get_shift_list(self):
return(self.shift_list)

def set_shift_list(self, shift_list):


self.shift_list = 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)}")

Shift_1 = Shift("001", 7.5, "Morning")


Shift_2 = Shift("002", 7.5, "Night")
Staff_1 = Staff Member("Khai Pham", [Shift_1, Shift_2])

Page 5 of 5

You might also like