[go: up one dir, main page]

0% found this document useful (0 votes)
111 views10 pages

BUSN5101 ExamRevisionQuestions

Uploaded by

Duy Bui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views10 pages

BUSN5101 ExamRevisionQuestions

Uploaded by

Duy Bui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Programming for Business: Exam Revision Questions

Exam Revision Questions


The following questions cover similar to the likely content and format of the Exam questions with
correct answers specified as well. You may wish to use this for helping with your preparation for the
Exam.

Question One
Design using Pseudocode and implement with Python 3, a set of two classes containing all the
features as exemplified in the lectures (i.e. constructor, accessors, mutators and _str_) function that
contain the following information:

- A class named ShoppingBasket which describes a basket of shopping; it will have a list of
product descriptions (e.g. “Milk”) and an item capacity (e.g. 240) as its attributes (class fields);

- A class named ShoppingTrolley which will contain all of the elements of the ShoppingBasket
but also contain the number of wheels which the trolley has (e.g. 4).

Then, in Python, create an instance of both classes to demonstrate their usage.

Answer One
CLASS ShoppingBasket:
NOTES: Describes a Shopping Basket.

ATTRIBUTES: product_descriptions
(List of Strings) item_capacity
(Integer / Whole Number)

CONSTRUCTOR: __init__
IMPORTS: self (current object), product_descriptions (List of Strings),
item_capacity (Integer / Whole Number)
EXPORTS: Nothing
NOTES: Constructs an instance of the ShoppingBasket
ALGORITHM: self.product_descriptions <-
product_descriptions self.item_capacity <-
item_capacity

ACCESSOR: get_product_descriptions
IMPORTS: self (current object)
EXPORTS: product_descriptions (List of Strings)
NOTES: Provides access to the product_descriptions attribute
ALGORITHM:
RETURN self.product_descriptions

ACCESSOR: get_item_capacity
IMPORTS: self(current object)
EXPORTS: item_capacity (Integer / Whole Number)
NOTES: Provides access to the item_capacity attribute
ALGORITHM:
RETURN self.item_capacity

MUTATOR: set_product_descriptions
IMPORTS: self (current object), product_descriptions (List of Strings)
EXPORTS: Nothing
NOTES: Changes the product_descriptions attribute

Page 1 of 10
Programming for Business: Exam Revision Questions

ALGORITHM:
self.product_descriptions <- product_descriptions

MUTATOR: set_item_capacity
IMPORTS: self (current object), item_capacity (Integer / Whole Number)
EXPORTS: Nothing
NOTES: Changes the item_capacity attribute
ALGORITHM: self.item_capacity
<- item_capacity

FUNCTION: __str__
IMPORTS: self (current object)
EXPORTS: string_rep (String – representation)
NOTES: Returns string representation of object.
ALGORITHM: string_rep <- self.product_descriptions AS
String + “ “ +
self.item_capacity AS String
RETURN string_rep

CLASS ShoppingTrolley INHERITS FROM ShoppingBasket:


NOTES: Describes a Shopping Trolley.

ATTRIBUTES: number_wheels (Integer


/ Whole Number)

CONSTRUCTOR: __init__
IMPORTS: self (current object), product_descriptions (List of Strings),
item_capacity (Integer / Whole Number), number_wheels
(Integer / Whole Number)
EXPORTS: Nothing
NOTES: Constructs an instance of the ShoppingTrolley
ALGORITHM:
CALL __init__ FROM super WITH product_descriptions, item_capacity
self.number_wheels <- number_wheels

ACCESSOR: get_number_wheels
IMPORTS: self (current object)
EXPORTS: number_wheels (Integer / Whole Number)
NOTES: Provides access to the number_wheels attribute
ALGORITHM:
RETURN self.number_wheels

MUTATOR: set_number_wheels
IMPORTS: self (current object), number_wheels (Integer / Whole Number)
EXPORTS: Nothing
NOTES: Changes the number_wheels attribute
ALGORITHM: self.number_wheels
<- number_wheels

FUNCTION: __str__
IMPORTS: self (current object)
EXPORTS: string_rep (String – representation)
NOTES: Returns string representation of object.
ALGORITHM: string_rep <- self.product_descriptions AS
String + “ “ + self.item_capacity AS String + “ “ +
self.number_wheels AS String
RETURN string_rep

Page 2 of 10
Programming for Business: Exam Revision Questions

class
ShoppingBasket():
“”” Describes a Shopping Basket. “””
def __init__(self, product_descriptions,
item_capacity): self.product_descriptions =
product_descriptions self.item_capacity =
item_capacity
def get_product_descriptions(self):
return(self.product_descriptions)
def get_item_capacity(self):
return(self.item_capacity)
def set_product_descriptions(self,
product_descriptions):
self.product_descriptions = product_descriptions
def set_item_capacity(self,
item_capacity):
self.item_capacity = item_capacity
def __str__(self): string_rep =
str(self.product_descriptions) + “ “ +\
str(self.item_capacity) return(string_rep)
class ShoppingTrolley(ShoppingBasket):
“”” Describes a Shopping Trolley. ”””
def __init__(self, product_descriptions, item_capacity,
number_wheels): super().__init__(product_descriptions,
item_capacity) self.number_wheels = number_wheels
def get_number_wheels(self):
return(self.number_wheels)
def set_number_wheels(self,
number_wheels):
self.number_wheels = number_wheels
def
__str__(self):
string_rep = str(self.product_descriptions) + “ “ +\
str(self.item_capacity) + “ “ + str(self.number_wheels)
return(string_rep)
shopping_trolley = ShoppingTrolley([“Milk”, “Eggs”], 20,
4) shopping_basket = ShoppingBasket([“Milk”, “Eggs”], 20)

Question Two
Write four Python functions as follows, ensuring you follow the conventions of the unit:

- A function that uses a list of numbers and another ‘single’ number which will insert the ‘single’
number into the list of numbers at the particular index element of the list of numbers that is the
same as said ‘single’ number (where it can be presumed that this will not cause an error). The
new list is then returned to the user.

- A function which prints out the contents (i.e. all the files and folders that are inside) of the
current working directory;

- A function which selects an item at ‘double random’ by first shuffling the order of elements in
the input list of numbers and then selects an element at random from the list and returns it;

- A function that returns the result of calculating the equation sin(x) 2 + cos(x)2 with the relevant
data provided as input parameters to the function;

Page 3 of 10
Programming for Business: Exam Revision Questions

Answer Two
def number_finder(list_numbers, single_number):
“”” Finds a number in a list. “””
list_numbers.insert(single_number, single_number)
return(list_numbers)
import os def
print_cwd():
“”” Prints the current working directory. “””
print(os.listdir(os.getcwd()))

import random
def select_double_random(input_list): “””
Selects a list at ‘double random’. “””
random.shuffle(input_list)
selected_item = input_list[random.randint(0, len(input_list) - 1)]
# Alternatively, the .choice function could be used.
return(selected_item)

import math
def
maths_calculator(x):
“”” Calculates a trigonometric value. “””
result = math.pow(math.sin(x), 2) + math.pow(math.cos(x), 2)
return(result)

Question Three
Utisiling the pandas and matplotlib libraries as taught in the unit, achieve the following tasks with the
creation of Python (3) code in the order stated below:

- Read in the sheet named “Example Sheet” from an Excel file named example_file.xlsx into a
DataFrame which should be named example_df;

- Convert a column named price_of_product to what would be the most appropriate data type
for the column (as implied by the name of the column);

- Create and show a scatter plot comparing two columns: cost_of_product and
price_of_product from the DataFrame (utilising its relevant method) where each scatter dot is
coloured green;

- Group the data by the unique values in a column named type_of_product and summarise the
remaining columns by generating their average value (assume that this is possible for all
remaining columns based upon their data types);

- Sort the grouped price_of_product values from the largest value first to the smallest value last;

- Write a copy of this grouped DataFrame to a file named output.csv.

Answer Three
import pandas as pd import
matplotlib.pyplot as plt
example_df = pd.read_excel(“example_file.xlsx”,
sheet_name = “Example Sheet”)

Page 4 of 10
Programming for Business: Exam Revision Questions

example_df[“price_of_product”] = example_df[“price_of_product”]\
.astype(float)
the_ax = example_df.plot(kind = “scatter”, x = “cost_of_product”,
y = “price_of_product, color = “green”) plt.show()
the_df = the_df.groupby(“type_of_product”).mean()
the_df = the_df.sort_values(“price_of_product”, ascending = False)
the_df.to_csv(“output.csv”)

Question Four
Assume you have a list of dictionaries in Python with the following contents and assignment:

the_dict = [{“name”: “Programming Service”, “cost”: 300.00}, {“name”: “Exam Study”, “cost”: 200.00},
{“name”: “Business Consulting”, “cost”: 400.00}]

Write the Python code required to filter the list of dictionaries such that only items (dictionaries) with a
cost value of over 200 remain in the list and then write the codes to write the dictionaries (using the
keys as headers) to a file named output.csv (hence, in the CSV format). Your code should be efficient
in the lines of code required and utilise the methods taught in the unit and be general enough that a
different list of dictionaries of the same format could use it. You should use the csv and json libraries,
alongside Python’s built-in functions to do so (i.e. do not use pandas or similar).

Answer Four
the_dict = list(filter(lambda x: x[“cost”] > 200.00, the_dict))
file_ptr = open(“output.csv”, “w”) csv_writer =
csv.writer(file_ptr)
csv_writer.writerow(list(the_dict[0].keys())) for each_dict in
the_dict: csv_writer.writerow(list(each_dict.values()))
file_ptr.close()

Page 5 of 10
Programming for Business: Exam Revision Questions

Exam Revision Questions (B)


The following questions cover similar to the likely content and format of the Exam questions with
correct answers specified as well. You may wish to use this for helping with your preparation for the
Exam.

Question One
Design using Pseudocode and implement with Python 3, a class containing all the features as
exemplified in the lectures (i.e. constructor, accessors, mutators and _str_ function) that stores the
information regarding a person – that is, it will store a full name, a date of birth and a list of mobile
telephone numbers.

Then, in Python, create two instances of the person class and populate each of the fields with data of
the most suitable data type. Retrieve and display in a human readable format the date of birth of both
persons (do not do this inside the accessor) and then change the mobile phone numbers. Finally,
output a string representation of each person.

Answer One
CLASS Person:
NOTES: Describes a Person.

ATTRIBUTES: full_name (String)


date_of_birth (datetime object)
mobile_phone_list (List of Strings)

CONSTRUCTOR: __init__
IMPORTS: self (current object), full_name (String), date_of_birth
(datetime object), mobile_phone_list (List of Strings)
NOTES: Constructs an instance of the Person
ALGORITHM: self.full_name <- full_name
self.date_of_birth <- date_of_birth
self.mobile_phone_list <- mobile_phone_list

ACCESSOR: get_full_name
IMPORTS: self (current object)
EXPORTS: full_name (String)
NOTES: Provides access to the full_name attribute
ALGORITHM:
RETURN self.full_name

ACCESSOR: get_date_of_birth
IMPORTS: self(current object)
EXPORTS: date_of_birth (datetime object)
NOTES: Provides access to the date_of_birth attribute
ALGORITHM:
RETURN self.date_of_birth

ACCESSOR: get_mobile_phone_list
IMPORTS: self(current object)
EXPORTS: mobile_phone_list (List of Strings)
NOTES: Provides access to the mobile_phone_list attribute
ALGORITHM:
RETURN self.mobile_phone_list

Page 6 of 10
Programming for Business: Exam Revision Questions

MUTATOR: set_full_name
IMPORTS: self (current object), full_name (String)
EXPORTS: Nothing
NOTES: Changes the full_name attribute
ALGORITHM:
self.full_name <- full_name

MUTATOR: set_date_of_birth
IMPORTS: self (current object), date_of_birth (datetime object)
EXPORTS: Nothing
NOTES: Changes the date_of_birth attribute
ALGORITHM: self.date_of_birth
<- date_of_birth

MUTATOR: set_mobile_phone_list
IMPORTS: self (current object), mobile_phone_list (List of Strings)
EXPORTS: Nothing
NOTES: Changes the mobile_phone_list attribute
ALGORITHM: self.mobile_phone_list <-
mobile_phone_list

FUNCTION: __str__
IMPORTS: self (current object)
EXPORTS: string_rep (String – representation)
NOTES: Returns string representation of object.
ALGORITHM: string_rep <- self.full_name AS
String + “ “ +
self.date_of_birth AS String WITH FORMAT “%d/%m/%Y” + “ “ +
self.mobile_phone_list AS String
RETURN string_rep

import datetime
class
Person():
“”” Describes a Person. “””
def __init__(self, full_name, date_of_birth,
mobile_phone_list): self.full_name = full_name
self.date_of_birth = date_of_birth self.mobile_phone_list =
mobile_phone_list
def get_full_name(self):
return(self.full_name)
def get_date_of_birth(self):
return(self.date_of_birth)
def get_mobile_phone_list(self):
return(self.mobile_phone_list)
def set_full_name(self,
full_name):
self.full_name = full_name
def set_date_of_birth(self,
date_of_birth):
self.date_of_birth = date_of_birth
def set_mobile_phone_list(self,
mobile_phone_list):
self.mobile_phone_list = mobile_phone_list
def __str__(self): string_rep =
str(self.full_name) + “ “ +\
self.date_of_birth.strftime(“%d/%m/%Y”) + “ “ +\
str(self.mobile_phone_list) return(string_rep)

Page 7 of 10
Programming for Business: Exam Revision Questions

person_a = Person(“Test Name”, datetime.datetime.now(), [12345678])


person_b = Person(“Toast Name”, datetime.datetime.now(), [23456789])
print(person_a.get_date_of_birth().strftime(“%d/%m/%Y”))
print(person_b.get_date_of_birth().strftime(“%d/%m/%Y”))
person_a.set_mobile_phone_list([34567890])
person_b.set_mobile_phone_list([45678901])
print(person_a)
print(person_b)

Page 8 of 10
Programming for Business: Exam Revision Questions

Question Two
Write two Python functions as follows, ensuring you follow the conventions of the unit:

- A function that asks the user to supply a string of a file path. This file path will be used inside
the function to list the files within the current working directory. One item of this current
working directory will be selected at random and returned to the user;

- A function which asks the user to supply a True or False value. If this value passed into the
function is true, then the sine of the current day of the month (in radians) is returned to the
user, however if the value is false then the cosine of the current day of the month (in radians)
is instead returned to the user instead. If the value is anything else, instead return the number
zero;

Answer Two
import os, random
def
random_file_chooser(file_path):
“”” Randomly selects a file from the file path. “””
file_list = os.listdir(file_path)
random_choice = random.randint(0, len(file_list) – 1)
# Could also use .choice
random_file = file_list[random_choice]
return(random_file)

import math, datetime


def
date_maths(do_sine):
“”” Function that calculates trigonometric formulae. “””
return_value = 0
current_day = int(datetime.datetime.now().strftime(“%d”))
if (do_sine == True):
return_value = math.sin(current_day)
elif (do_sine == False):
return_value = math.cos(current_day)
else: return_value = 0
return(return_value)

Question Three
Utilising the pandas and numpy libraries as taught in the unit, achieve the following tasks with the
creation of Python (3) code in the order stated below:

- Create a numpy array of the sequential integer numbers from 1 to 25 inclusive;

- Reshape the numpy array into a 5x5 matrix and print the result to the user;

- Create a Pandas DataFrame that contains the same data as the 5x5 numpy array (you do not
have to use the numpy array to do this) and then print it;

- Set each of the columns in the DataFrame to be named sequential capital letters (i.e. the first
column is A and so forth for how many columns there are in this instance);

Page 9 of 10
Programming for Business: Exam Revision Questions

- Create a new column in the DataFrame named XX which is half of the value of the first
column and (added to) two times the value of the third column;

- Adjust the data type of the (original) second and fourth columns of the DataFrame to be
floating point numbers.

Answer Three
import numpy as np import
pandas as pd

twenty_five_numbers = list(range(1, 26))


numpy_array_tf = np.array(twenty_five_numbers, dtype = int)
numpy_array_rs = numpy_array_tf.reshape(5, 5) print(numpy_array_rs)

example_df = pandas.DataFrame([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12,


13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]])
example_df.columns = [“A”, “B”, “C”, “D”, “E”]
example_df[“XX”] = 0.5 * example_df[“A”] + 2 * example_df[“C”]
example_df[“B”] = example_df[“B”].astype(float) example_df[“D”]
= example_df[“D”].astype(float) print(example_df)

Question Four
Assume you have a list of sets in Python with the following contents and assignment:

the_sets = [{1, 2, 3}, {2, 3, 4}, {4, 5, 6}, {7, 8, 9}]

Write the Python code required to adjust the list of sets such that each set will now also contain the
number 0 alongside the current items within each set. Next, combine each of the sets within the list so
you end up with one set (in a new variable) that only contains the unique elements between each of
the sets. Then, print this new set to the screen. After this, write each element of the set to a new line
within a file named example.txt. Your code should be efficient in the lines of code required and utilise
the methods taught in the unit and be general enough that a different list of sets of the same format
could use it. You should use the csv and json libraries, alongside Python’s built-in functions to do so
(i.e. do not use pandas or similar).

Answer Four
the_sets = [{1, 2, 3}, {2, 3, 4}, {4, 5, 6}, {7, 8, 9}] for
each_set in the_sets:
each_set.add(0)
all_sets = the_sets[0] | the_sets[1] | the_sets[2] | the_sets[3]
print(all_sets)
the_file = open("example.txt", "w") for
each_element in all_sets:
the_file.write(str(each_element) + “\n”)
the_file.close()

Page 10 of 10

You might also like