CS1026 ASSIGNMENT 1 to 4 solutions

$90.00

Original Work ?
Category: You will Instantly receive a download link for .ZIP solution file upon Payment

Description

5/5 - (1 vote)

CS1026 ASSIGNMENT 01 Friends Dinner

INTRODUCTION

In this assignment, you will get practice with:
Basic Python programming constructs
Expressions, decisions
Getting input from users
Algorithm development and testing; designing test cases
Following program specifications
loops
As you organize a dinner assembly for your closest friends at a restaurant in your city, you find yourself searching
for the perfect place to dine.

After much contemplation, you decide to take your companions to a restaurant that
accommodates the dietary restrictions of your friends. Therefore, you decided to write a Python program inquiring
about any Keto, vegan, or gluten-free dietary needs among your party members and subsequently listing the
suitable meals for dinner. Table I shows the available meals according to the dietary restrictions accommodated in
this restaurant.

If the invitee has a different dietary preference that does not match any of the meals in the menu above, a
beverage is offered for $5.99

ASSIGNMENT WAKTHROU!

To make it easier for you, please have a look at the video below. The video walks through the important parts
of the assignment. In addition to some extra tests that shows the input/output.
TOP

1 FILES
For this assignment, you are asked to submit one file named dinner.py containing all the code required to
complete this assignment.

Your program should run according to the following specifications:
0:00 / 17:45
The program will ask the user to specify the number of invitees by showing the message
“Please enter the number of invitees:”
The user is expected to enter a positive integer representing the number of invitees. We assume that the
user will always provide valid input.

1
According to the number of invitees, your program should loop over all the invitees to gather information
about each individual’s dietary preferences. This is accomplished as follows:
Show the user the invitee number that you are taking the information about. You should show the
message
“Please enter the order details for invitee Number X/Y”
where X is the invitee number and Y is the number of invitees.

The program will then ask the user if the invitee has a Keto diet with the message
“Do you want a keto friendly meal?”
If the user answers (y lowercase) that means yes. Anything else, even the word “yes” should be
considered no.

The program will then ask the user if the invitee prefers a vegan meal with the message
“Do you want a vegan meal?”
If the user answers (y as lowercase) that means yes. Otherwise, it is considered no.
The program will then ask the user if the invitee prefers a Gluten-free meal with the message
2
TOP
“Do you want a Gluten-free meal?”
If the user answers (y lowercase) that means yes. Otherwise, it is considered no.
Your program should decide what is the appropriate meal from the menu according to the collected
dietary preference for each invitee. e.g., if the user enteres y then y then y, your program should
serve Falafel for this particular friend. If the user enterss no then n then y, the program should
serve beverage for this friend as none of the meals in the menu satisfies this preference.

The program should keep asking the user these questions until all invitees’ preferences are collected.
When all the information is gathered, your program will ask the user to tip the server by entering a positive
number representing the percentage of the total bill to be given as a tip. The program will show
“How much do you want to tip your server (% percent)?”

And the user is assumed to enter a positive integer for the tip. E.g., if the user entered 15, this means that
the tip is 15% of the total cost after tax.
3

The program then will display the order details as the following 5 lines:
Your program prints
“You have X invitees with the following orders:”
where X is the number of invitees.
Your program then prints
“Y invitees ordered Pizza. The cost is: $N”
where Y is the number of invitees who ordered pizza and N is the total cost for only those people,
rounded to two decimal points.

Your program then prints
“Y invitees ordered Pasta. The cost is: $N”
where Y is the number of invitees who ordered Pasta and N is the total cost for only those people,
rounded to two decimal points.
Your program then prints
“Y invitees ordered Falafel. The cost is: $N”
where Y is the number of invitees who ordered Falafel and N is the total cost for only those people,
rounded to two decimal points.

Your program then prints
“Y invitees ordered Steak. The cost is: $N”
where Y is the number of invitees who ordered Steak and N is the total cost for only those people,
rounded to two decimal points.
Your program then prints
“Y invitees ordered only beverage. The cost is: $N”
where Y is the number of invitees who ordered beverage and N is total cost for only those people,
rounded to two decimal points.
4

The program then will display the total cost of the bill in three lines as follows:
Your program prints
“The total cost before tax is $H ”
where H is the total cost to all orders before any tax. H is printed to the nearest two decimal places.
5
TOP

Functional Specifications

Your program will execute as described above. The following are a few examples of the inputs and the expected
outputs:
Case 1:
Case 2:
Case 3:
Your program then prints
“The total cost after tax is $N ”
where N is the total cost to all orders after tax which is 13% of the total cost. You should use the total
cost calculated in the previous step, H, to print N. And, N is printed to the nearest two decimal places.

Your program then prints
“The total cost after X% tip is $Y”
where X is the tip percentage, and Y is the total cost to all orders after the tip. You should use the total
cost calculated in the previous step, N, to print Y. And, Y is rounded to the nearest integer. You can use
the following equation to calculate Y:

Non-Functional Specifications

The program should strictly adhere to the input and output requirements, particularly the order of the input
and the labelling of the output cost.
The program should include brief comments in your code identifying yourself, describing the program, and
describing key portions of the code.

You should be bothered with writing meaningful code comments to help others, including the grading team,
understand your code. A code comment that describes:
Identifying yourself
Describe the program and the reasoning behind it
Its input(s) and output(s)

Describing key portions of the code
An example of a good comment practice:
Assignments must be done individually and must be your work. Software may be used to detect academic
dishonesty (cheating).
Use Python coding conventions and sound programming techniques. For example:
Meaningful variable names
Conventions for naming variables and constants
Use of constants where appropriate
Readability, indentation, and consistency

2 TIPS AND GUIDELINES

Variables should be named in lowercase for single words and camel case for multiple words, e.g.,
noOfInviteesOrderedPizza
You can assume that all values entered are valid. You do not need to check if the input is valid
Make sure to use the exact wording and spacing of the messages prompted to the user. You can copy/paste it
for your convenience.

Include all the puncuations as demonstrated in the examples. This is bacause marking will be very sensitive to
formatting.

Testing Your Program
Wondering how to verify the effectiveness of your solution? Developing a set of test cases can assist in checking
the thoroughness and precision of your code. While the abovementioned examples are not exhaustive, they will aid
in this pursuit.

However, please note that the success of these test cases does not guarantee the complete
correctness and completeness of your code. It is important to consider additional test cases that will further
confirm the completeness and accuracy of your provided solution. You can create an excel sheet to calculate and
compare what you get in the sheet with the output of your code.

3 RULES
Read and follow the instructions carefully.
Only submit the Python file described in the Files section of this document.
Submit the assignment on time. Late submissions will receive a late penalty of 10% per day.
Forgetting to submit a finished assignment is not a valid excuse for submitting late.
Submissions must be done on Gradescope. They will not be accepted by email.

You may re-submit your code as many times as you would like. Gradescope uses your last submission as the
one for grading by default. There are no penalties for re-submitting. However, re-submissions that come in
after the due date will be considered late and subject to penalties.

REMEMBER!
Make sure you develop your code with Python 3.9 or higher as the interpreter. Failure to do so may result in
the testing program failing.

Assignments will be run through a similarity checking software to check for code that looks very similar to
that of other students. Sharing or copying code in any way is considered plagiarism and may result in a mark
of zero (0) on the assignment and/or reported to the Dean’s Office. Plagiarism is a serious offence. Work is to
be done individually.

4 MARKING GUIDELINES
The assignment may be marked as a combination of your auto-graded tests and manual grading of your code logic,
comments, formatting, style, etc. Below is a breakdown of the marks for this assignment:
[50 marks] Testing your code for correctness and adherence to the specifications by producing the expected
output
[20 marks] Code logic and completeness
[10 marks] Comments
[10 marks] Code formatting
[10 marks] Meaningful and properly formatted variables
Total: 100 marks

– GRADESCOPE SUBMISSION
REMEMBER!
The weight of this assignment is 5% of the course mark.
You must submit the 1 files to the Assignment 1 submission page on Gradescope. The required file is
dinner.py .
1
The submission will be using Gradescope.

You can find the instruction on how to complete your submission by following the steps in this video:
2

REMEMBER!
Assignment submission after 11:55 PM will cause late penalty of 10% per day to be deducted from your
mark.
Submissions through the email will not be accepted at any circumstances.
Please check back this page whenever an announcement is posted regarding this assignment.
TOP

CS1026B A2: The PC Shop

1. Introduction

Congratulations! You are finally launching the business you’ve been planning for
years – an online PC shop! This shop will allow customers to buy from one of two
main categories: custom builds (a computer that is built and customized to meet
specific customer needs) and pre-built machines (complete systems assembled by
well-known manufacturers using balanced hardware configurations).

You
currently only carry a relatively small (but powerful) inventory of items, but you
want to give your customers the best experience possible anyways. You will be
writing a program (using Python) that allows users to order items from your shop.

In this assignment, you will get practice with:
– Creating functions
– Calling functions and using returned values
– User input in a loop
– Conditionals
– Lists, 2-D lists, and tuples
– String formatting for clean output

To begin, let’s note a few things. If your customers are building a computer, they
absolutely must have these essential parts:
1. Central Processing Unit (CPU) for executing instructions
2. Motherboard for allowing communication between crucial components of
the system
3. Random Access Memory (RAM) for storing information that needs to be
retrieved quickly

4. Power Supply Unit (PSU) for powering the components within the system
5. Either a Solid State Drive (SSD) or a Hard Disk Drive (HDD) (or both) for
storage
6. A case for storing the components

Often, people will also want a Graphics Card to add to their build if they plan on
doing things like gaming, video editing, or 3D graphics modeling in which
processing graphical data as efficiently as possible is important.

With that out of the way, let’s also note that sometimes certain PC parts are not
compatible with each other within a build (for example, an Intel i7-11700K CPU
and an MSI B550-A PRO motherboard are not compatible) and the PC will not
work when a build is attempted. Your shop tries to ensure that all components
can be used together in a build, however sometimes it’s just not possible.

** Note that you do not need to know about component compatibility beyond
what is explicitly being told to you for this assignment.

2. Files

For this assignment, you must create one file: shop.py. Note that this file should
by shop.py precisely (not Shop.py, shop.py.py, or any variation of these things).

3. Instructions

In the shop.py file, create a function called pickItems() which takes no parameters
and acts as the heart of the program. This function will mainly consist of a userinput-driven system for ordering PCs, but can (and definitely should) get help
from separate helper functions (you’ll decide what those helper functions are and
what they do).

The pickItems() function will walk the user through their order
using print statements and collecting user input, and will ultimately return a list
with the prices of each PC a user has purchased (whether they built it
themselves or bought a pre-built).

3.1 Storing your inventory as a list of lists
You have a static inventory (we’ll assume you have unlimited resources of each
offered item). The types of PC components you have in stock for custom builds
are listed below (and can be copied directly into your shop.py file):
SSD = [[‘1’, ‘250 GB’, 69.99], [‘2’, ‘500 GB’, 93.99], [‘3’, ‘4 TB’, 219.99]]
HDD = [[‘1’, ‘500 GB’, 106.33], [‘2’, ‘1 TB’, 134.33]]

CPU = [[‘1’, ‘Intel Core i7-11700K’, 499.99], [‘2’, ‘AMD Ryzen 7 5800X’, 312.99]]
MOTHERBOARD = [[‘1’, ‘MSI B550-A PRO’, 197.46], [‘2’, ‘MSI Z490-A PRO’, 262.30]]
RAM = [[‘1′, ’16 GB’, 82.99], [‘2′, ’32 GB’, 174.99]]
GRAPHICS_CARD = [[‘1’, ‘MSI GeForce RTX 3060 12GB’, 539.99]]
PSU = [[‘1’, ‘Corsair RM750’, 164.99]]
CASE = [[‘1’, ‘Full Tower (black)’, 149.99], [‘2’, ‘Full Tower (red)’, 149.99]]

And the types of pre-built machines you have to offer are:
PREBUILTS = [[‘1’, ‘Legion Tower Gen 7 with RTX 3080 Ti’, 3699.99], [‘2’,
‘SkyTech Prism II Gaming PC’, 2839.99], [‘3’, ‘ASUS ROG Strix G10CE Gaming PC’,
1099.99]]

In these 2-D lists, the inner-list structure represents:
[the ID associated with that component (string), the name of the product being
offered (string), and the price of the product (float)]

3.2 Hardware Incompatibilities
As mentioned previously, some components are incompatible with each other.
For example, some motherboards do not have the correct CPU socket (and
supported chipset) for certain CPU models (this is all jargon you don’t need to be
familiar with, but could research if you were interested).

When looking at the hardware we offer, we notice that the Intel Core i7-11700K
CPU is NOT compatible with the MSI B550-A PRO motherboard, and the AMD
Ryzen 7 5800X CPU is NOT compatible with the MSI Z490-A PRO motherboard.
This needs to be taken into consideration when showing customers what
components are available for their build.

If the user is building a custom machine and chooses option ‘1’ for their CPU (Intel
Core i7-11700K), your program should only present and allow them to select
option ‘2’ (MSI Z490-A PRO) to them within the motherboard selection. If the user
selects option ‘2’ for their CPU (AMD Ryzen 7 5800X), the program should only
present and allow them to select option ‘1’ (MSI B550-A PRO) within the
motherboard selection stage. Examples of this are shown below.

3.3 Storage Selection
When purchasing storage (where data is permanently stored on your computer),
the customer can either select an HDD, an SSD, or both. Thus, you must allow
them to decline purchasing the HDD or the SSD if they wish. To ‘decline’, the user
should be able to input ‘x’ OR ‘X’. If the user has already declined purchasing an
SSD, you must ensure that they select a HDD. Examples of this are shown below.

3.4 Order of Component Selection
It is important to note that customers MUST purchase one CPU, one
motherboard, one RAM option, one PSU option, one SSD or HDD (or BOTH – they
can decline purchasing one or the other if they wish), and one case. In addition,
recall that they do not NEED to purchase a graphics card – they can decline with
‘x’ or ‘X’.

Once your program is launched, If the user wishes to build a custom PC, they must
enter 1. Then, you should guide them through their options in the exact order of:
CPU, Motherboard (making sure the motherboards shown are compatible with
the CPU they have just chosen), RAM, PSU, the case, SSD, HDD, and Graphics
card.

This ensures that, during testing, our input is matching up with what your
program is expecting. If you do not prompt the user to select the components in
this order, the autograder will fail all of the test cases and you will receive a
mark of 0 on that portion.

3.5 Ensuring the Customer Enters a Valid Input
When the user selects an invalid option (one that does not appear as available for
selection), the program should continue prompting for input until their entry is
valid, as shown in the image below. We can see here that the program continues
asking for input until a valid option is chosen.

When choosing a graphics card, ensure that ‘x’ and ‘X’ are included in the
allowable input (as the user does not necessarily need one).
When choosing storage, ensure that ‘x’ and ‘X’ are included in allowable input for
the HDD if the user selected an SSD. If the user did not select an SSD, ensure that
‘x’ and ‘X’ are not included in the allowable input.
For all other necessary hardware, the user should not be able to select ‘x’ or ‘X’
(as these parts are required).

3.6 What is Returned from pickItems()?
When building a custom-build, once all of the parts are successfully picked, the
total price of all the parts combined should be added to a list that will eventually
be returned from pickItems() (once the user selects that they’re ready to
checkout with ‘3’). The user, if they wish, can also continue to either build
another PC (by pressing ‘1’), or add a pre-built PC to their cart (by pressing ‘2’).
The pickItems() function should return a list of prices of each PC ordered by one
customer in the order that they were purchased.

Again, one customer could
order as many custom-built and pre-built machines as they wish (before pressing
‘3’ to checkout) and the total price of each should be returned in a list in the
order that the customer purchased them once they do press ‘3’ to checkout.
Note that if the user does not order anything, an empty list should be returned.

3.7 The Final Print Statement
After the user selects ‘3’ to checkout, you should simply print the list that is
returned from pickItems().

3.8 Other Important Notes
After completing a custom-build, you should print ‘You have selected all of the
required parts! Your total for this PC is $___’ where ‘___’ is replaced with the
price for that specific PC. If a pre-built is added, you should print ‘Your total price
for this pre-built is $___’ where ‘___’ is replaced with the price for that specific
pre-built.

This allows the user to know how much every individual PC costs before checking
out.

4. User Interaction

The following five images demonstrate the expected flow of the program.

Important Notes:

– The number that the user inputs needs to be the number in the first index
of the item they are selecting, otherwise known as the ID (for example, if
they are purchasing 32GB of RAM, they need to enter ‘2’. This is so that
when we test your code in Gradescope, our input will match up with the
values that your program is looking for.

– If the user can decline selecting an item (for example, the SSD, HDD, or
Graphics card), allow them to select ‘X’ (they should be able to enter a
capital ‘X’ or lowercase ‘x’) in order to not purchase that piece of hardware.
– The exact text that you print to the user should be as similar as possible to
the examples provided above. This makes grading easier.

Hints:
– You must ensure that the user is only selecting one of the offered values
(for example, for the SSD, those values would be ‘1’, ‘2’, ‘3’, ‘x’, or ‘X’). To
do this, you could write a helper function like ‘extract(list)’ that returns a
list of the FIRST element of each list within the list of hardware. So, for SSD,
it would return [‘1’, ‘2’, ‘3’] (and then you could add ‘x’ and ‘X’ manually)

The usage could look something like:
while (SSD_pick not in extract(SSD) and SSD_pick != ‘x’ and SSD_pick != ‘X’):
SSD_pick = input(‘Choose the number that corresponds with the
part you want (or X to not get an SSD): ‘)
This will keep querying the user for a value until they enter an ‘permitted’
value.
– When a user is purchasing a HDD, you should check if they have already
purchased an SSD (and had not pressed ‘x’ or ‘X’). This can be done with a
simple ‘if-else’ statement. If they have, you can allow ‘x’ or ‘X’ to be an
allowable input. If they haven’t, you should ensure that they choose one of
the available HDD options so that the PC will work upon building it.

Tips and Guidelines

– Add comments throughout your code to explain what each section of the
code is doing and/or how it works. This is crucial in obtaining part-marks.
– Ensure that both ‘x’ and ‘X’ work as inputs to the program, where they are
applicable.
– You are encouraged to create and run your own tests to ensure that your
code works in many different cases (you can also use the images provided
within this document to determine whether your program is working as
expected or not).

– When submitting your assignment on Gradescope, please submit shop.py
only.
– Ensure that when printing prices, you are using two digits after the decimal
point.

Rules
– Read and follow the instructions carefully.
– Only submit the python file described in the files section of this document.
– Submit the assignment on time. Late submissions will receive a late penalty
of 10% per day (except where late coupons are used).
– Forgetting to submit a finished assignment is not a valid excuse for
submitting late.
– Submissions must be done on Gradescope. They will not be accepted by
email.

– You may re-submit your code as many times as you would like. However,
re-submissions that come in after the due date will be considered late and
subjected to late penalties.

– Assignments will be run through a similarity checking software to check for
code that looks very similar to that of other students. Sharing or copying
code in any way is considered plagiarism and may result in a mark of zero
(0) on the assignment and/or reported to the Dean’s Office. Work is to be
done individually.

Submission

Assignments cannot be submitted by email, only through Gradescope.

Marking Guidelines
The assignment will be marked as a combination of your auto-graded test results,
manual grading of your code logic, comments, formatting, style, etc. Below is a
breakdown of the marks for this assignment:
[50 marks] Auto-graded Tests
[20 marks] Code logic and completeness
[10 marks] Comments
[10 marks] Code formatting
[10 marks] Meaningful and properly formatted variables
Total: 100 marks

CS 1026 Assignment 3 Creating an Information System for Electronic Medical Records

1) Background

In Canada, we are seeing the need to improve the healthcare system. What many people don’t realise is that our healthcare system still makes use of very primitive information systems like excel sheets, fax machines, and even paper written records. There is a ton of room for improvements that we as Computer Scientists can make.

Image: Health Tech and Interface For example, Electronic Medical Records (EMRs) are becoming increasingly important in the healthcare industry, providing a way for doctors and other healthcare professionals to access a patient’s medical history, diagnosis, and treatment plans all in one place. By automating the process of collecting, storing, and analyzing patient data, EMRs help to improve the quality of care, reduce errors, and increase patient safety.

Assignment Intro Video

This video is required to watch as it summarises the assignment. Brief Video to Introduce the Assignment Context of Assignment and Future Applications The following video provides some context on the benefit and impacts of design of software used in hospitals.

This video is optional, but recommended to understand the issues in health information systems. https://youtube.com/watch?v=DBC89rs_9I8&si=EnSIkaIECMiOmarE

Context Video: Issues with Health Information Systems Scope and Context In this programming assignment, you will be creating a Health Information System that uses biomedical signals to produce an electronic medical record for each patient. The system will read patient data from a plain-text file that is separated by commas, allowing new patient information to be added through user input to update the plain-text file..

In programming, the term “backend” refers to the part of a software system or application that is responsible for handling data processing, and other functionality that is not directly visible to the user. This includes database management, and other aspects of a system that do not involve the user interface (UI). The backend is typically responsible for processing requests and delivering data to the frontend (user-facing part of the software) for display to the user. It is often designed to be scalable, flexible, and able to handle large volumes of data efficiently. Electronic Health Records: Usability and Unintended Safety Issues

Though we will not be focusing on User-Interface design (UXD) in this assignment, your work in this assignment will provide a possible core information system “backend” to help improve a healthcare system. Assignment Walk-Through Video by Prof (Required) Thank you for your help in improving the healthcare system! 2) Program Features The program will provide the following features, plus more as described in the function sections below: A function to read patient data from a plaintext file. A function to display various statistics about the patients, such as the average vital signs about the patients or for a specific patient.

A function to display patient data for all patients or for a specific patient by ID. A function to add new patient data to the patient list. A function to find patient visits in a certain month or year A function to find patients who need follow-ups depending on their vital statistics A text-based interface to list the patients and allow the user to select which feature they would like to use. 3) Dataset We will use a text file containing data from patient visits in a file, called “patients.txt”. The file contains one line for every unique visit by any patient to the clinic.

Note that it is possible that each patient may visit the clinic multiple times. The file has the following columns, with each data element being separated with a comma and each new record on a new line. The data in the file will look like the following: https://youtu.be/ENaKj1crDVA

This data will be structured with the delimiter being a comma, and the types of information as follows: Patient ID Integer Date of visit (YYYY-MM-DD) String Body temperature (Celsius) Float Heart rate (beats per minute) Integer Respiratory rate (breaths per minute) Integer Systolic blood pressure (mmHg) Integer Diastolic blood pressure (mmHg) Integer Oxygen saturation (%) Integer A full sample dataset is available online with the .txt extension.

For testing purposes, you are strongly encouraged to create your own datasets following the above convention to test your code more thoroughly. 4) File to Hand In and Provided Files You are provided a sample main.py file with indications where you’ll put your own implementation. You will submit one file – named “main.py” to Gradescope. Please do not modify the main function in this file. 1 2 3 4 5 6 1,2022-06-01,37.2,72,16,120,80,97 1,2022-09-15,37.5,73,18,125,82,96 2,2022-06-10,36.9,69,18,123,80,96 2,2023-01-03,37.1,71,19,124,81,97 3,2022-08-05,37.3,74,20,126,83,95 3,2023-03-01,37.4,75,18,123,79,98

Links to Provided Files: main.py (https://1drv.ms/u/s!As0vrM-NsbcQkpYwuuCIP0JbvqxyJQ?e=eAK5SM) This file contains the definitions of the functions you will write, as well as the main program the creates the interface. You will write code to implement these functions as per the specifications at the location indicated by a comment “#Put your code here”. patients.txt (https://1drv.ms/t/s!As0vrM-NsbcQkpYvHATJ4v-zz3CIcA?e=LSHQJi) This is one sample dataset containing visits of patients and their medical data. You can use this for testing.

We encourage you to modify it and test with different data. 5) Learning Outcomes and Skills Used Using functions: Consider the use of functions to break down the tasks into smaller, more manageable parts. E.g., implement functions for reading patient data from a file, displaying patient data, adding new patient data, and calculating patient statistics. Complex data structures: Use complex data structures, such as dictionaries and lists, to store and manipulate patient data.

Text processing: We will use text processing to read and write patient data to and from a text file. File input and output: We will implement functions to read and write patient data to a text file. Exceptions in Python: Consider handling exceptions in our code. For example, consider how to handle cases where the data in the text file is not in the correct format, or has an extra blank line at the end. Using Python modules: We should use Python modules as applicable, to make the code more efficient and readable. Adhering to specifications by testing programs and developing test cases: Remember to adhere to the specifications given and test the programs using test cases.

6) View of Information System Interface you will Create Sample View from User’s Perspective 7) General Tips Break down the tasks into smaller, more manageable parts. This will make the code easier to write and easier to maintain. Use meaningful variable and function names. This will make the code easier to read and understand. Function names are provided.

Use docstrings to document the functions. This will make the code easier to understand and maintain. Docstrings are provided. Write detailed comments in the code. Not only is this part of your grade for the assignment, but it’s building a best-practice for when you are doing coding projects with others after this course is over. Test the code using your own test cases. This will help identify and fix bugs in the code. Feel free to make other input files, and plan out your user inputs to see if code works as expected.

8) Starting To help you get started, we have provided function declarations and docstrings for each of the above features. We have also included tips for each function to help you implement them effectively. Remember to test your code using test cases to make sure it is working as expected. Good luck! 9) Function 1: readPatientsFromFile() Note the following correction made to Function 1 requirements This function reads patient data from a plaintext file and returns a dictionary, returns a dictionary where each key is a unique patient ID and the corresponding values are 2-dimensional lists storing information about each visit (where each visit’s information is stored in its own inner-list)

Correction summary: number ranges in “Errors to Handle” section – made on 2023-03-17  Correction Details: Old Vs New “Errors to Handle” section to make Function 1 be consistent with Function 4    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 def readPatientsFromFile(fileName): “”” Reads patient data from a plaintext file. fileName: The name of the file to read patient data from. Returns a dictionary of patient IDs, where each patient has a list of The dictionary has the following structure: { patientId (int): [ [date (str), temperature (float), heart rate (int), respirator [date (str), temperature (float), heart rate (int), respirator … ], patientId (int): [ [date (str), temperature (float), heart rate (int), respirator … ], … } “””

Functionality Reads patient data from a plaintext file specified by the fileName argument. Returns a dictionary of patient IDs, where each patient has a list of visits. Each visit is a list of 7 values in the order of date, temperature, heart rate, respiratory rate, systolic blood pressure, diastolic blood pressure, and oxygen saturation, in this order.

Performs additional data validation checks to ensure the data is within reasonable ranges (as listed below) If any of the data is invalid or an error occurs (the list of errors is listed below), the function skips the line that contains the error, and continues reading the next line in the file. Errors to Handle Changelog: Please note that the ranges in this section were corrected to match the ranges in Function 4 on Mar 17. If the file specified by fileName cannot be found, print the message: “The file ‘[fileName]’ could not be found.” and the program exits.

You can assume that you will be passed a file name and not a path. If there is an unexpected error while reading the file, print the message: “An unexpected error occurred while reading the file.” And skips to the next line. If the number of fields in a line is not equal to 8, print the message: “Invalid number of fields ([numFields]) in line: [line]” And skips to the next line If the patient ID or any of the other 7 data values are not in the correct format, print the message: “Invalid data type in line: [line]” And skips to the next line If the temperature value is not within the range of 35 to 42, print the message: “Invalid temperature value ([temp]) in line: [line]” And skips to the next line If the heart rate value is not within the range of 30 to 180,

print the message: “Invalid heart rate value ([hr]) in line: [line]” And skips to the next line If the respiratory rate value is not within the range of 5 to 40, print the message: “Invalid respiratory rate value ([rr]) in line: [line]” And skips to the next line If the systolic blood pressure value is not within the range of 70 to 200, print the message: “Invalid systolic blood pressure value ([sbp]) in line: [line]” And skips to the next line

If the diastolic blood pressure value is not within the range of 40 to 120, print the message: “Invalid diastolic blood pressure value ([dbp]) in line: [line]” If the oxygen saturation value is not within the range of 70 to 100, print the message: “Invalid oxygen saturation value ([spo2]) in line: [line]” And skips to the next line Exact Output Formatting Each error message should be printed exactly as specified in the requirements, with the appropriate variable values filled in. if any of the error messages are printed, we do not add this visit to the dictionary at all, and we move on to the next line What should the dictionary contain?

If the input file looked like this: Your dictionary would look like this: Test Cases For examples on how to test other inputs, please watch the extended assignment intro video. 1 2 3 4 5 6 1,2022-06-01,37.2,72,16,120,80,97 1,2022-09-15,37.5,73,18,125,82,96 2,2022-06-10,36.9,69,18,123,80,96 2,2023-01-03,37.1,71,19,124,81,97 3,2022-08-05,37.3,74,20,126,83,95 3,2023-03-01,37.4,75,18,123,79,98   1 {1: [[‘2022-06-01’, 37.2, 72, 16, 120, 80, 97], [‘2022-09-15’, 37.5, 73, 18 Case 1: Information invalid  Case 2: Information valid and successful import 

10) Function 2: displayPatientData() This function displays patient data for all patients or a given patient ID. Functionality The function takes in a dictionary patients containing patient data where each patient has a list of visits, and a patientId (default 0) which represents the ID of the patient to display data for. If patientId is 0, then the function displays data for all patients. The function prints patient data for the specified patientId or for all patients if patientId is 0.

For each patient, the function prints the patient ID and data for each visit including visit date, temperature, heart rate, respiratory rate, systolic blood pressure, diastolic blood pressure, and oxygen saturation. Errors to handle If patientId is not found in patients, the function should print an error message “Patient with ID {patientId} not found.” And the program will go back to the main menu Additional error checking (e.g, checking if patients are not a dictionary, or patient ID is negative or not an integer, etc.) is not necessary in this function. Exact output required For each patient, the function prints the patient ID followed by data for each visit.

For each visit, the function prints: Visit Date: {visit date in yyyy-mm-dd format} Append 1 space to start of each visit so it appears indented from patient ID, e.g.   1 2 3 4 5 6 7 def displayPatientData(patients, patientId=0): “”” Displays patient data for a given patient ID. patients: A dictionary of patient dictionaries, where each patient has patientId: The ID of the patient to display data for. If 0, data for al “”” 1 print(” Visit Date:”, visit[0])

Temperature: {temperature value} C Append 2 spaces to each health stat so it appears indented from visit date, e.g. Heart Rate: {heart rate value} bpm Respiratory Rate: {respiratory rate value} bpm Systolic Blood Pressure: {systolic blood pressure value} mmHg Diastolic Blood Pressure: {diastolic blood pressure value} mmHg Oxygen Saturation: {oxygen saturation value} % The function should not return anything. Test cases 11) Function 3: displayStats()

This function prints the average of each vital sign for all patients or for a specified patient. 1 print(” Temperature:”, “%.2f” % visit[1], “C”) 1) Print all cases  2) Patient is not in data  3) Patient is found in data    1 2 3 4 5 6 7 def displayStats(patients, patientId=0): “”” Prints the average of each vital sign for all patients or for the speci patients: A dictionary of patient IDs, where each patient has a list of patientId: The ID of the patient to display vital signs for. If 0, vita “””

Functionality: The function should display the average vital signs of all patients or a specific patient, depending on the value of the patientId parameter (which should default to 0). If patientId is 0, the function should display the average of each vital sign for all patients contained in the data, as a single average (not per patient). If patientId is a positive integer, the function should display the average vital signs for the specified patient. If the specified patientId is not found in the patients dictionary, an error message print(“No data found for patient with ID {}.”) should be displayed, and the program will go back to the main menu.

The function should display the following vital signs with their respective units: Average temperature in degrees Celsius (°C) Average heart rate in beats per minute (bpm) Average respiratory rate in breaths per minute (bpm) Average systolic blood pressure in millimeters of mercury (mmHg) Average diastolic blood pressure in millimeters of mercury (mmHg) Average oxygen saturation as a percentage (%) If no data is found for the specified patient or for all patients, a message indicating that no data was found should be displayed (as above), and the program will go back to the main menu.

Errors to handle If patientId is not an integer, an error message should be displayed, print(“Error: ‘patientId’ should be an integer.”) and then return to the main menu If the patients parameter is not a dictionary, an error message should be displayed: Print (“Error: ‘patients’ should be a dictionary.”) and then return to the main menu Output format The function should display the vital sign values rounded to exactly two decimal places of precision. The function should display each vital sign on a separate line with a specific message structure, as follows:

If patientId is 0, the message should start with “Vital Signs for All Patients:” followed by the average vital sign value and unit. If patientId is a positive integer, the message should start with “Vital Signs for Patient {patientId}:” followed by the average vital sign value and unit. The vital sign should have 2 spaces inserted so it appears tabbed in from the line “Vital signs for Patient …” e.g. If no data is found for the specified patient or for all patients, the function should display a message with the structure “No data found” and the program will go back to the main menu. Test Cases 12) Function 4: addPatientData() This function adds new patient data to the patients dictionary and appends this same data to the text file. 1 print(” Average temperature:”, “%.2f” % (temp_sum / num_visits), “C”) 1) Patient ID is not an integer  2) Patient ID is 0  3) Patient ID is positive integer  4) Patient ID is not found in data 

Requirements

Requirements for the implementation of addPatientData() function are: The function should take in a dictionary of patient IDs as patients, where each patient ID has a list of visits. The function should take in the following parameters for adding new patient data: patientId, date, temp, hr, rr, sbp, dbp, and spo2. The function should take in a file name as fileName and append the new data to this file.

You can assume that we will use the same text file to write to as was read in using the readPatientsFromFile() function The function should check the inputs and handle erroneous input as below. The function should add the new data to the patient’s visit history by appending the visit information to the text file. The function should display an error message if any input value is invalid and return to the main menu without adding the new data. Errors to Handle Edit note – this section updated 2023-03-15 to clarify the errors.

If any of the following errors occur, the program should display the exact corresponding message and return to the main menu   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 def addPatientData(patients, patientId, date, temp, hr, rr, sbp, dbp, spo2 “”” Adds new patient data to the patient list by appending to the dictiona patients: The dictionary of patient IDs, where each patient has a list patientId: The ID of the patient to add data for. date: The date of the patient visit in the format ‘yyyy-mm-dd’. temp: The patient’s body temperature. hr: The patient’s heart rate. rr: The patient’s respiratory rate. sbp: The patient’s systolic blood pressure. dbp: The patient’s diastolic blood pressure. spo2: The patient’s oxygen saturation level. fileName: The name of the file to append new data to. “””

If the date format is invalid, print “Invalid date format. Please enter date in the format ‘yyyymm-dd’.” If the date is cannot exist, e.g., the 35 day of a month or a 14 month, etc, print “Invalid date. Please enter a valid date.” Further clarification 2023-03-21- Only a simple check is required, so DD must be in the range 1-31, MM must be in range 1-12, and year should be 1900 or more recent. Future dates are allowed. You do not need to add more advanced logic for the number of days per specific month (you don’t need to check if Feb is <= 28 days, or handle leap years, etc.) If the temperature is invalid, print “Invalid temperature.

Please enter a temperature between 35.0 and 42.0 Celsius.” If the heart rate is invalid, print “Invalid heart rate. Please enter a heart rate between 30 and 180 bpm.” If the respiratory rate is invalid, print “Invalid respiratory rate. Please enter a respiratory rate between 5 and 40 bpm.” If the systolic blood pressure is invalid, print “Invalid systolic blood pressure. Please enter a systolic blood pressure between 70 and 200 mmHg.” If the diastolic blood pressure is invalid, print “Invalid diastolic blood pressure. Please enter a diastolic blood pressure between 40 and 120 mmHg.”

If the oxygen saturation level is invalid, print “Invalid oxygen saturation. Please enter an oxygen saturation between 70 and 100%.” If an unexpected error occurs (any exception), print “An unexpected error occurred while adding new data.” Exact Output Required The function should display a success message after adding the new data. If the new data is successfully added, print “Visit is saved successfully for Patient #”, and return to the main menu Test Cases th th 1) Invalid

13) Function 5: findVisitsByDate() This function finds the visits by date provided and returns a list of tuples. See below. Functionality: The function should take in a dictionary of patient IDs, where each patient has a list of visits, as well as an optional year and/or month to filter the visits by. The function can accept a year only, or both a year and a month. It can’t accept a month only: If the year is only provided, the function returns all visits occurred in that year regardless of the month and day. If the month and year are provided, the function returns all visits occurred in that month of the provided year regardless of the day.

If no year and/or month is provided, the function should return all visits for all patients. The function should ignore visits in the dataset with incomplete or invalid date information (i.e. dates that are missing year, month, or day). For example, if the text file contained: 2) Out of range health stat (oxygen saturation)  3) Valid input    1 2 3 4 5 6 7 8 9 def findVisitsByDate(patients, year=None, month=None): “”” Find visits by year, month, or both. patients: A dictionary of patient IDs, where each patient has a list of year: The year to filter by. month: The month to filter by. return: A list of tuples containing patient ID and visit that match the “”” 1 2 3 4 5 6 1,2022-06-01,37.2,72,16,120,80,97 1,2022-09-15,37.5,73,18,125,82,96 2,2022-07-10,36.9,69,18,123,80,96 2,2023-01-03,37.1,71,19,124,81,97 3,2022-08-05,37.3,74,20,126,83,95 3,2023-03-01,37.4,75,18,123,79,98

And month: 6 and year 2022 was provided, your function should return this: Errors to Handle The function should handle the case where the patient dictionary is empty, or where the patient dictionary is not empty, but there are no visits in the given year/month . In these cases, your program should return an empty list. The function should handle the case where an invalid year or month is provided (e.g, the 14 month or 35 day, etc) by ignoring the filter and returning an empty list.

Output Format The function should return a list of tuples where each tuple contains the patient ID (an integer) and visit (a list). The visit list should contain the following information in this order: date (a string in the format ‘yyyy-mm-dd’), temperature (a float), heart rate (an integer), respiratory rate (an integer), systolic blood pressure (an integer), diastolic blood pressure (an integer), and oxygen saturation (an integer). Test Cases   1 [(1, [‘2022-06-01’, 37.2, 72, 16, 120, 80, 97]), (2, [‘2022-06-10’, 36.9, 6 th th 1. Invalid date  2. Input just a year  3. Input a month and year (data does not exist)  4. Input a month and year (data exists) 

14) Function 6: findPatientsWhoNeedFollowUp() Functionality The function takes in a dictionary of patient IDs and their visits as input. It checks each visit of each patient for abnormal vital signs (heart rate, systolic and diastolic blood pressure, and oxygen saturation level) using if conditions. If any visit has any of the abnormal vital signs, the patient’s ID is added to the followup_patients list. For the assignment, we’ll assume if any of the following are true, the patient needs a followup Heart rate > 100 or heart rate is < 60 or systolic is > 140 or diastolic is > 90 or blood oxygen saturation is < 90: The function returns a list of patient IDs that need follow-up visits.

If no patients require a follow-up, return an empty list. Errors to handle None. Exact output required The function should return a list of integers representing the patient IDs that need follow-up visits. Note that the main program provided will handle printing this list out for you. For debugging/testing purposes, consider printing out the contents of your list, then removing this print statement before submitting.   1 2 3 4 5 6 7 def findPatientsWhoNeedFollowUp(patients): “”” Find patients who need follow-up visits based on abnormal vital signs. patients: A dictionary of patient IDs, where each patient has a list of return: A list of patient IDs that need follow-up visits due to abnorma “””

Test Cases 15) Function 7: deleteAllVisitsOfPatient() Functionality: The function deleteAllVisitsOfPatient deletes all visits of a particular patient from the patients dictionary. It rewrites the text file with the updated patient data. Arguments: patients: A dictionary of patient IDs, where each patient has a list of visits. patientId: The ID of the patient to delete data for. filename: The name of the file to save the updated patient data. Returns: None Errors to handle: If patientId is not found in patients, print “No data found for patient with ID {patientId}”.

1. Case At least 1 health metric is cause for a followup  2. Case No patients need followup    1 2 3 4 5 6 7 8 9 def deleteAllVisitsOfPatient(patients, patientId, filename): “”” Delete all visits of a particular patient. patients: The dictionary of patient IDs, where each patient has a list patientId: The ID of the patient to delete data for. filename: The name of the file to save the updated patient data. return: None “””

Output: If data for the patient with patientId is deleted, print “Data for patient {patientId} has been deleted.”. No output if patientId is not found in patients. File Writing Requirements: 1. The function should open the specified file in write mode (‘w’). It is important to note that the w mode will overwrite the data currently in the file, but you will need to write all remaining patients and visits back to the file. When testing this function, your code will actually delete the records from the text file. You will need to re-download the text file to “reset” for your next test.

2. The function should iterate over the dictionary of patient data and write each remaining visit for each patient to the file in comma-separated format after removing the deleted patients visit(s) . The format for each line in the file should be: where patientId is the ID of the patient, date is the date of the visit in the format yyyy-mm-dd, temp is the patient’s body temperature, hr is the patient’s heart rate, rr is the patient’s respiratory rate, sbp is the patient’s systolic blood pressure, dbp is the patient’s diastolic blood pressure, and spo2 is the patient’s oxygen saturation level.

Note that there is no space before or after the commas, and each line should end with a newline character (\n). 3. After writing all the visits to the file, the function should close the file. Test Cases 1 patientId,date,temp,hr,rr,sbp,dbp,spo2\n 1. Case patient exists  2. Case patient does not exist 

16) Marking Guidelines 1. The assignment will be marked as a combination of your auto-graded test results, manual grading of your code logic, comments, formatting, style, etc. Below is a breakdown of the marks for this assignment: [50 marks] Functionality – Auto-graded Tests [20 marks] Comments [10 marks] Code logic and completeness [10 marks] Code formatting [10 marks] Meaningful and properly formatted variables Total: 100 marks We hope these tips help you get started with the Health Information System programming assignment. Remember to test your code using test cases to make sure it is working as expected. Good luck! © Corporatez Theme (http://a2themes.com/details/corporate/corporatez-ex)

CS1026 ASSIGNMENT 04 AVIATION SYSTEM

INTRODUCTION

In this assignment, you will get practice with:
Creating classes and objects
Constructors, getters, setters, and other instance methods
Loading data from text files
Cleaning and parsing data from text files
Working with dictionaries and sets
Algorithm development and testing
Designing test cases

Following program specifications
Air travel is one of the most popular, efficient, and safe methods of transportation, especially for long-distance
travels. As we approach the summer season, we can expect that millions will be travelling by airplanes to visit
family or friends. Airlins and air travel agencies helps connect people around the globe using aviation management
systems.

In this assignment, you are asked to implement a program that loads text files representing some of the
airports and flights around the world and analyzes the flights according to specifications.
Some of the data in these files are not necessarily real/accurate.

1 FILES

In this assignment, there are 3 types of text files that will need to be read in using your code. These three files are
already provided to you. When reading the file please consider:
You can assume that the data in these three files is case-insensitive.
The data is separated by commas (,).

You don’t need to validate the data. You can assume that the data is correct. However,
The data is not cleaned. You need to clean the data from extra white spaces and tabs.
Empty lines should be ignored.
countries.txt

This file contains a set of lines with comma separated values. Each line contains a country name and the continent
name that the country belongs to. Some of the lines contain spaces and/or tabs around the individual portions of
the line that must be cleaned up when being read in. You can assume that all the lines are separated correctly
with commans and no other delimiter is used.

A small snippet showing the format of an countries file:
airports.txt
This is the airports file which lists a number of airports around the world. Each line in this file contains a single
airport and it shows the 3-letter airport code, the country in which the airport is located, and then the city in which
the airport is located.

These three items are separated by commas. Some of the lines contain spaces and/or tabs
around the individual portions of the line that must be cleaned up when being read in. You can assume that all the
lines are separated correctly with commans and no other delimiter is used.
A small snippet showing the format of an airport file:
flights.txt

The other file is the flights file that contains a list of flights including a 6-character flight code, the origin airport
code, and the destination airport code. Each line in the file represents one flight. Again, there may be spaces and/or
tabs around the individual portions of the line that must be cleaned up when being read in.

Again, you can assume
that all the lines are separated correctly with commans and no other delimiter is used.
A small snippet showing the format of a flights file:

For this assignment, you must create three (3) Python files: Airport.py , Flight.py , and Aviation.py .
Airport.py
The Airport file must contain a class called Airport. Every method in this file must be in the Airport class. Do not
have any code in the file that isn’t part of this class. (Do not include functions calls, a main function, input(), etc. as
this may result of the autograder to fail. This is your responsibility).

As suggested by its name, this class represents an Airport in the program. Each Airport object must have a unique
3-letter code which serves as an ID, a city, country and a continent which all are strings representing its
geographical location.
Within the Airport class, you must implement the following methods based on these descriptions and
specifications:
When submitting your assignment on Gradescope, please submit these 3 files only. Do not upload any other
files.

Make sure the files are named EXACTLY as specified here.
REMEMBER
You MUST implement all classes, methods (with parameters names), functions listed in the description
below, with THE EXACT SAME NAMES (case sensitive). Failure to comply with this may result into a potential
loss of marks. However, you are welcome to add more helper functions/methods as long as you you
implement the required ones.

Please, adhere with the EXACT formatting of the outputs and return values. Pay attention to the punctuation
used, paranthesis, brackets. “It is only a comma” is not a valied execuse :). Extra space here or there is fine.
__init__(self, code, city, country, continent):

Initialize the instance variables _code, _city, _country, and _continent based on the corresponding
parameters in the constructor
1

Flight.py
The Flight file must contain a class called Flight. Note that this file must import from Airport as it makes use of
Airport objects. Therefore, you need to add the follwoing line to the top of the Flight file.:
from Airport import *

Other than this import line, everything in this file must be in the Flight class. Do not write any other code in the file
that isn’t part of this class. (No input, no function calls outside the class, etc. Again this is your responsibility 🙂 )

As suggested by the class name, this class represents a Flight from one Airport to another Airport in the program.
Each Flight object must have a flightNo (a unique 6-character code containing 3 letters followed by 3 digits) as a
string, an origin airport, and a destination airport. Both the origin and destination must be Airport objects within the
program.

Within the Flight class, you must implement the following functions based on these descriptions and specifications:
__repr__(self)
Return the representation of this Airport in the following format:
{code} ({city}, {country})
e.g., YYZ (Toronto, Canada)
2
getCode(self)
Getter that returns the Airport code
3
getCity(self)
Getter that returns the Airport city
4
getCountry(self)
Getter that returns the Airport country
5
getContinent(self)
Getter that returns the Airport continent
6
setCity(self, city)
Setter that sets (updates) the Airport city
7
setCountry(self,country)
Setter that sets (updates) the Airport country
8
setContinent(self,continent)
Setter that sets (updates) the Airport continent
9
__init__(self, flightNo, origAirport, destAirport)

First check that both origAirport and destAirport are Airport objects (hint: use the isinstance function).
If either or both are not Airport objects, raise a TypeError exception that states:
“The origin and destination must be Airport objects”
1

In the case that the flightNo is not a string of 6-character code containing 3 letters followed by 3
digits, raise a TypeError exception that states:
“The flight number format is incorrect”
When the origAirport and destAirport are both Airport objects, proceed to initialize the instance
variables _flightNo, _origin, and _destination based on the corresponding parameters in the
constructor.
__repr__(self)

Return the representation of this Flight containing the flightNo, origin city, and destination city, and an
indication of whether the Flight is domestic or international (see the isDomesticFlight method description
below). The representation must be in the following format:
Flight({flightNo}): {originCity} -> {destinationCity}
{[domestic]/[international]}
Examples:
Flight(MCK533): Toronto -> Montreal [domestic]
Flight(WCL282): Toronto -> Chicago [international]
2
__eq__(self, other)

Method that returns True if self and other flights are considered the same flight. Two flights are considered
the same if the origin and destination are the same for both Flights i.e., self and other. Make sure that if
“other” variable is not a Flight object, this means False should be returned.
3
getFlightNumber(self)
Getter that returns the Flight number string code
4
getOrigin(self)
Getter that returns the object of the Flight origin
5
getDestination(self)
Getter that returns the object of the Flight destination
6
isDomesticFlight(self)

This method returns True if the flight is domestic, i.e. within the same country (the origin and destination
are in the same country); However, it returns False if the flight is international (the origin and destination
are in different countries).
7
setOrigin(self, origin)
Setter that sets (updates) the Flight origin
8
setDestination(self, destination)
Setter that sets (updates) the Flight destination
9

Aviation.py
This file is meant to be the core of the program from which the Airport and Flight objects should be created as their
corresponding text files are loaded in; and several functionalities must be implemented to analyze the data and
retrieve results about specific queries.

Since this file will be used to create Airport and Flight objects, both of those Python files must be imported into this
one. To do this, add the following lines of code to the top of this file:
from Flight import *
from Airport import *

You need to create the class Aviation as the name suggests. Apart from the aforementioned two import lines, all
the content of this file should relate only to the Aviation class. (No input, no function calls outside the class, etc.
Again this is your responsibility 🙂 ). The following methods needs to be implemented based on these descriptions
and specifications:
__init__(self)

The constructor will not accept any external parameter. However, you then need to create several instance
variables. Three containers, self._allAirports, self._allFlights, and self._allCountries to store all the Airport
objects, Flight objects, and counrties with continents respectively. The _allAirports, _allCountries
containers can be any type you wish (i.e. list, set, or dictionary, etc.); However, the _allFlights container
MUST be a dictionary.

1
3 setters: getAllAirports, getAllFlights, getAllCountries and 3 getters: setAllAirports, setAllFlights,
setAllCountries for _allAirports, _allFlights, _allCountries.
2
loadData(self, airportFile, flightFile, countriesFile):
Read in all the data from the countries file of the given name the parameter, countriesFile. Extract the
information from each line. Remove any whitespace from the outside of each portion of the line (not
just the line itself). To add all the file contents to the _allCountries container, we suggest to create it as
a dictionary. For each line in the file you add a new element to the _allCountries dictionary so that the
key is the country name while the value is the continent name.

Read in all the data from the airports file of the given name the the parameter, airportFile. Extract the
information from each line and create an Airport object for each. Remove any whitespace from the
outside of each portion of the line (not just the line itself). As you create each Airport object, add the
object to the _allAirports container. Review the format of the airports file as well as the order in which
the parameters are expected in the Airport constructor to ensure you send in the correct values for
the correct parameters. Don’t forget to use the _allCountries dictionary while creating the Airport
objects.

Read in all the data from the flights file of the given name through the parameter, flightFile. Extract
the information from each line and create a Flight object for each. Remove any whitespace from the
outside of each portion of the line (not just the line itself). As you create each Flight object, add the
object to the _allFlights dictionary in this specific way: the key must be the origin’s airport code and
the corresponding value must be a list of the Flight object(s) that depart from this origin airport. For
3

example, if “YYZ” is an entry in this dictionary, its value would be a list of all Flight objects in which the
Flight’s origin is “YYZ” (all flights that go out from Pearson airport). Review the format of the flights
file as well as the order in which the parameters are expected in the Flight constructor to ensure you
send in the correct values for the correct parameters.

If all files load properly without errors, return True. If there is any kind of exception that occurs while
trying to open and read these files, return False. Use a try-except statement to handle these cases
and make sure to close the files properly.
When reading the text files, use the following line
f = open(filename, “r”, encoding=’utf8′)

The encoding parameter should be ‘utf8’ (nevermind why should we use this).
getAirportByCode(self, code)
Return the Airport object that has the given code (i.e. YYZ should return the Airport object for the YYZ
(Pearson) airport). If there is no Airport found for the given code, just return -1.
4
findAllCityFlights(self, city)

Return a list that contains all Flight objects that involve the given city either as the origin or the destination
5
findFlightByNo(self,flightNo)
Returns a flight object of with the flight number equals to flightNo. Return -1 if not found.
6
findAllCountryFlights(self, country)

Return a list that contains all Flight objects that involve the given country either as the origin or the
destination (or both).
7
findFlightBetween(self, origAirport, destAirport)
Check if there is a direct flight from origAirport object to destAirport object. If so, return a string of the
format:
Direct Flight(flightNo): origAirportCode to destAirportCode
i.e. Direct Flight(ABC456): YYZ to ORD

Otherwise, if there is no direct flight, check if there is a single-hop connecting flight from origAirport
to destAirport. This means a sequence of exactly (2 flights, 3 airports) such that the first flight begins
in origDestination and ends in some airport “X”, and the second flight goes from airport “X” to
destAirport. like:
origAirport —-> X —-> destAirport

Create and return a set (not a list) of all possible “X” airport codes representing the airports that could
serve as the connecting airport from origAirport to destAirport. Do not include the origAirport and
destAirport in the set. Do not worry about multiple-hop connections as that becomes very
complicated to track.

You should only look at single-hop connecting flights. Like, we are not interested
in such flights:
origAirport —-> X —-> Y —-> destAirport
origAirport —-> X —-> Y —-> …. —-> destAirport
Again, this should only be done if there was no direct flight.
8

If there is no direct flight AND no single-hop connecting flights from origAirport to destAirport, then
just return -1.
findReturnFlight(self, firstFlight)

Take the given Flight object (firstFlight) and look for the Flight object representing the return flight from that
given flight. In other words, given firstFlight from origin A to destination B, find the Flight object that
departs from origin B and arrives in destination A.

The method should return this returning flight object. If
there is no such Flight object that goes in the opposite direction as firstFlight, just return -1.
9
findFlightsAcross(self, ocean)

This method takes an ocean name as a parameter. The value of this parameter is either of two values:
“Atlantic”, “Pacific” as strings. You can assume that this value is always sent correctly.
In the image below, you can see the world map divided into three zones.
North America and South America in the green zone.
Asia and Australia in the red zone.
Africa and Europe in the blue zone.

A flight crosses the Pacific if the origin is the from one of the countries in the green zone and the
destination is to one country in the red zone or vice versa.
On the other hand, a flight crosses the Atlantic if the origin is the from one of the countries in the green
zone and the destination is to one country in the blue zone or vice versa.

This method will return a set (not list) of all the flight codes that cross the specified ocean, or return -1 if
there is no flights.

Tester File (Asst4Tests.py)
You are provided with a file called Asst4Tests.py. This file will run tests to check that each of your classes and
methods are working as expected. You can uncomment the tests one by one to test the functionalities separately
and isolate potential problems.

Gradescope may also use different files (same format but different names and data) so your program should not
have anything hardcoded.

If you are failing one or more tests, you should look at what the test is checking for and each of the sub-tests
within that test (most tests are checking 2-4 different cases to ensure it works for all those cases). It may help to
print out each of test case values, i.e.
print(t1)
print(t2)
print(t3)

You should also add other print lines to help debug and narrow down the source of the errors in your code. Make
sure to remove these temporary print lines once finished debugging.
You can also create your own testing environment and test your code as you’re developing it. You then can use
Asst4Tests.py after you complete the code.

GRADESCOPE TESTING!
It is your responsibility to do thorough testing to ensure the code works not just for the given tests and data
but for many different test cases and different sets of data.

DEBUGGING!
It is very highly encouraged to use the debugging tools for this assignment. Remember, this assignment
includes a complex structure, so, 80% of the time spent in this assignment is on fixing problems.

USER INPUT!
The three files that you need to submit does NOT ask for user input at any point. They are basically consist of
class definitions and function definitions.

EXCEPTION HANDLING!
Remember to handle all expected exceptions in your code. Failure to do so may result in incomplete execution
of your code in Gradescope and potential marks loss.

Functional Specifications

Your program must work for any airports file and flights file. The format will be the same, but they could have
different names and a different list of airports or flights. Your program must work with the files of the given names,
so do not hardcode it to only work for the files provided to you.

The Asst4Tests.py file is a great way to test that your functions are working according to specifications. However,
you must do your own testing in addition to the tests given in this file. The Gradescope autograder may run
additional tests that are not visible to you, so your program should be well-tested to ensure it works not just for
the given tests but in a large multitude of test cases.

Non-Functional Specifications

The program should strictly adhere to the requirements and specifications of these classes and functions.
The program should include brief comments in your code identifying yourself, describing the program, and
describing key portions of the code.

Assignments are to be done individually and must be your own work. Software may be used to detect
academic dishonesty (cheating).
Use Python coding conventions and good programming techniques. For example: Meaningful variable names
Conventions for naming variables and constants
Use of constants where appropriate
Readability, indentation, and consistency
The name of the files you submit must be Airport.py, Flight.py, and Aviation.py

2 TIPS AND GUIDELINES

Variables should be named in lowercase for single words and camel case for multiple words, i.e. origAirport
Do not hardcode filenames, numbers of lines from the files, or any other variables
You can assume that the file formats for each of the 2 types of text files will be the same for any file being
used for testing. You may not assume that the number of lines nor the values stored in them will be the same.
Add comments throughout your code to explain what each section of the code is doing and/or how it works
3 RULES
Read and follow the instructions carefully.
Only submit the Python file described in the Files section of this document.

Submit the assignment on time. Late submissions will receive a late penalty of 10% per day .
Forgetting to submit a finished assignment is not a valid excuse for submitting late.
Submissions must be done on Gradescope. They will not be accepted by email.

You may re-submit your code as many times as you would like. Gradescope uses your last submission as the
one for grading by default. There are no penalties for re-submitting. However, re-submissions that come in
after the due date will be considered late and subject to penalties.

Assignments will be run through a similarity checking software to check for code that looks very similar to
that of other students. Sharing or copying code in any way is considered plagiarism and may result in a mark
of zero (0) on the assignment and/or reported to the Dean’s Office. Plagiarism is a serious offence. Work is to
be done individually.

4 MARKING GUIDELINES
The assignment will be marked as a combination of your auto-graded tests (both visible and hidden tests) and
manual grading of your code logic, comments, formatting, style, etc. Below is a breakdown of the marks for this
assignment:
[50 marks] Auto-graded Tests
[20 marks] Code logic and completeness
[10 marks] Comments
[10 marks] Code formatting
[10 marks] Meaningful and properly formatted variables
Total: 100 marks

– GRADESCOPE SUBMISSION
REMEMBER!
The weight of this assignment is 10% of the course mark.
You must submit the 3 python files to the Assignment 4 submission page on Gradescope. The required files
are Airport.py , Flight.py , and Aviation.py . Please, dont’t submit and other files.
1
Double check the files names and the extensions to be .py. No other file names or extensions will be
considered.

2
Make sure again that there is no user input, no function calls outside the class, and no unhandled
exceptions. Failure to do so may result in your code being stuch while grading.
3

The submission will be using Gradescope.
You can find the instruction on how to complete your submission by following the steps in this video:
4

REMEMBER!
Assignment submission after 11:55 PM will cause late penalty of 10% per day to be deducted from your
mark.
Submissions through the email will not be accepted at any circumstances.
Please check back this page whenever an announcement is posted regarding this assignment.
TOP