Lab9 v6
Lab9 v6
Goal
Tasks
Deadline:
It is an academic offense to copy code from other students, provide code to other students, let
other people (including the teaching staff) debug your code, or debug other students’ code.
Note: For question 3 – 6, you must come up with a function description in your own words,
and cannot copy the words from handout.
Write a function called calculate_average() that takes a string in the given format as input and
returns the average of the numbers as a floating-point value.
You are highly recommended to attempt the questions yourself before you look at the
solution as a way to learn.
Q1.1 Start by completing signature and design recipe of the function calculate_average().
You are tasked with calculating the average of numbers in a string format. The numbers are
separated by '|', and there could be spaces around the numbers and separators. Your task is to
write a Python function to calculate this average. The input string will always contain exactly 5
numbers in the specified format.
Solution:
So how do we write a script to achieve the functionality? Recall that one of the principles we
mentioned in the first lecture is that we use building blocks to build systems. Let’s break down
the problem. Please note that you can use the same procedure for complicated problems in the
future.
Recall that in the previous labs, your code usually has the following the structure:
• Take the input and the check for the preconditions
• Do some calculation with the input
Solution:
For do some calculation with the input, let’s see what the structure of our script should look like
if our example is “2| 7|5| 10 |11”:
Our goal here is to write a script that can handle any expressions in this format, not just “2|
7|5| 10 |11” So let’s generalize our structure:
1. Take the input in the format of “x1 | x2| x3 | x4|x5”
2. Do some calculation with the input
2.1 Find the number in “x1 | x2| x3 | x4|x5”
2.2 Split the list based on ‘|’, we will get [“x1 ”, “ x2”, “ x3 ”, “ x4”, “x5”]
i. For each element in the list, remove the space before and after
ii. Convert to integer
2.3 Sum all the numbers
2.4 Divide by the number of numbers (in this case, 5)
3. Show the result
Solution:
After splitting the string, you should ensure that there are exactly 5 elements (numbers)
in the resulting list. If there are not exactly 5 elements, it indicates an invalid input. We
want to make sure that the input string contains exactly 5 numbers, as this is a
requirement. To do this, we use an 'assert' statement to check if the number of
elements in the list matches the expected count of 5.
Note: We skipped the precondition checking of whether there are numbers of strings,
but not alphabetic characters. Think about how to check it?
Solution:
To find the average, we need the total sum of the 5 numbers. We iterate through the list
of numbers, remove any leading or trailing spaces, and convert each number to an
integer. Then, we calculate the sum of these integers.
Note: the current coding style isn't ideal. We encourage you to refactor your code next
week to improve your coding style.
Once you have the total sum of the numbers, you should calculate the average by dividing the
total by 5 (since there are 5 numbers). And you should return the calculated average as a float.
Solution:
Note (again!) the current coding style isn't ideal since we haven't covered looping over
collections yet. We'll be learning about it in the next class. We encourage you to refactor your
code next week to improve your coding style.
We skipped a few things in the code, you are encouraged to think about those after
completing the lab as additional exercises:
• Please note that here we skip the precondition check for each element (e.g.,
each must be an int). You can think about how to check these to guarantee that
all numbers are integers.
• If we need to accept floating numbers, then how would you change the
precondition check?
• We used a naïve way of calculating the average, can you think of ways to
calculate the result with built-in functions?
Submission
• Go to eClass -> our course -> Week 9 -> Practice -> Lab -> Lab 9 Submission
• You can resubmit your code as many times as you need, but you need to wait for 5
minutes before submission (You need spend some time debugging!).
Rubrics:
• You will get full mark for this question if you submit the solution (with no typo) to the
required location on Prairielearn before the deadline.
Note:
• Since we provide solutions to this question, it is ok to submit it as is.
• In order for the autograder to work properly:
o You must NOT change the name of the function
o You must NOT change the order of the arguments
• The autograder may take some time to grade
For example when the input list is [10, 10, 30, 40], the output should be {'apple': 10, 'banana':
10, 'grape': 30, 'orange': 40}
However, it seems that there are some issues with the function. Your task is to identify and fix
the problems to make the function work correctly.
The code to debug (lab9_task2.py) may have syntax errors, run-time errors, semantic errors, or
errors in test cases. To help with debugging, you can use the debugger to execute the code line
by line (you should fix the syntax errors before doing this).
After completing the question, you can think about why Sam wants to do this conversion.
What are the limitations of using a list?
Note (again!) the current coding style isn't ideal since we haven't covered looping over
collections yet. We'll be learning about it in the next class. We encourage you to refactor your
code next week to improve your coding style.
Requirement
• You must not change the function definition
Submission
● Copy the Python code to Lab 9 -> Task 2 on Prairielearn.
● You can resubmit your code as many times as you need, but you need to wait for 5
minutes before submission
Rubrics:
• You will not receive any mark if you do not submit it to the designated location on
Prairielearn before the deadline
• You will not receive any mark if your code violates the above requirements
• Otherwise
Given a dictionary called inventory to represent the store's inventory, where keys are product
names (strings) and values are the quantities (integers) of each product in stock. For example:
inventory = {
"Laptop": 20,
"Smartphone": 15,
"Tablet": 30,
"Headphones": 10
}
This function returns the current quantity of the item. Below are two examples of how
add_to_inventory should work. As shown in the example, add_to_inventory returns the new
product quantity.
In the first example, we add 5 Keyboards. Since Keyboard does not exist in the original
inventory, we add this new item and the quantity is 5. Thus, the quantity to return is the
quantity of this inventory, which is 5.
In the second example, we add 10 Smartphones. Smartphone already exist in the original
inventory with a quality of 15. Thus the quantity to return is 15 + 10 = 25.
Submission
● Copy the Python code to Lab 9 -> Task 3 on Prairielearn.
● You can resubmit your code as many times as you need, but you need to wait for 5
minutes before submission.
• You will not receive any mark if your code violates the above requirements
• Otherwise
o You will receive 0.5 pt for doctest (At least 4, and they cannot be the cases
below)
o You will receive 1 point if your script correctly provides the correct solution for a
general test case, e.g.,
§ Ans: 5
o You will receive 1 point if your script correctly provides the correct solution for
edge case – empty inventory, e.g.,
§ Ans: 1
o You will receive 1 points if your script correctly provides the correct solution for
edge case – singleton inventory, e.g.,
§ Ans: 7
o You will receive 1 point if your script correctly provides a solution for condition –
the item to be added was not in inventory, e.g.,
§ Ans: 30
o You will receive 1 point if your script correctly provides a solution for condition –
the item to be added was already in inventory, e.g.,
o You will receive 1 point if your script correctly provides a solution for violation
of contract, e.g.,
§ Ans: AssertionError
o you will receive 3 points for providing a solution for three other test cases (1 pt
each)
For example, one input might be "aBce_aabe_bCC", in this case the three strings to consider
would be "aBce", "aabe" and "bCC". The output of the function will be a list containing the
intersecting characters in ascending order. The output of the above example would be ['b', 'c']
as 'b' and 'c' are the only characters appearing in all three strings. The intersecting characters
are case-insensitive and your answer should be in all lowercase.
input: a string
"_CCda_acz"
[]
reasoning:
'a' and 'c' are in the second and third string, but there are no characters in the first string,
therefore there are no characters appearing in all three strings.
- input may be invalid (more than, or less than 2 "_" characters. In this case you should
assert an error)
- you can match characters across strings in a case-insensitive manner but your answer
should be in all lowercase
Hint: This task can be done with loops but it will be easier if you use collections. You can convert
a list to a set by wrapping it with set(). For example, if you had the following list
>>> x = [1, 1, 5, 1, 2, 3, 1]
>>> set(x)
{1, 5, 2, 3}
Requirement
● You cannot use any other libraries or packages to get the answer for you
● You can resubmit your code as many times as you need, but you need to wait for 5
minutes before submission
Rubric
● You will not receive any mark if you do not submit it to the designated location on
Prairielearn before the deadline
● You will not receive any mark if your code violates the above requirements
● Otherwise
○ You will receive 0.5 pt for doctest (At least 4, and they cannot be the cases
below)
o You will receive 1 pt if your script correctly provides the solution to: General
case, e.g., "ab_aaab_bCC", ans: ['b']
o You will receive 1 pt if your script correctly provides the solution to: Condition –
have common characters but with both upper and lower case, e.g.,
"aBcd_aaab_bCC", ans: ['b']
o You will receive 1 pt if your script correctly provides the solution to: Condition –
have common characters but with common upper cases only, e.g.,
"Bdk_YB_MWB", ans: ['b']
o You will receive 1 pt if your script correctly provides the solution to: Condition –
no common character, e.g., "m_CCda_acz", ans: []
o You will receive 1 pt if your script correctly provides the solution to: Condition –
Multiple common characters, e.g., "CAB_cab_cxaxb", ans: ['a', 'b', 'c']
o You will receive 1 pt if your script correctly provides the solution to: Violation of
contract, e.g., "za3g34_0a_a", ans: AssertionError
o You will receive 3 pts if your script correctly provides the solution to other
examples (3 cases and 1 pt each)
In this task, you will implement a function and no starter code is provided. The function should
be called remove_item and accept two arguments. Given a list of the name of products and the
name of the product to remove from the list, the function should return a list with the product
removed. For example:
>>> remove_item(["cellphone", "laptop", "microphone"], "laptop")
['cellphone', 'microphone']
The items in the list can be any string and there is no other specifications of the format of the
string.
Submission
Copy the Python code to Lab 9 -> Task 5 on Prairielearn.
You can resubmit your code as many times as you need, but you need to wait for 5 minutes
before submission (You need to spend some time debugging!).
Rubrics:
• You will not receive any mark if you do not submit it to the designated location on
Prairielearn before the deadline
• You will not receive any mark if your code violates the above requirements
• Otherwise
o You will receive 0.25 pts if you provide a description of the function.
o You will receive 0.25 pts if you provide the argument annotations correctly
o You will receive 0.5 pt if you include at least 2 test cases (and they cannot be the
same as test cases provided) and your code pass those test cases
o You will receive 1 pts if your function passes general test (e.g.,
remove_item(["cellphone", "laptop", "microphone"], "laptop"), expected
output: ['cellphone', 'microphone'] )
o You will receive 1 pts if your function passes the corner test - zero data (e.g.,
remove_item([], "laptop"), expected output: [] )
o You will receive 1 pts if your function passes the corner test - singleton data
(e.g., remove_item(["laptop"], "laptop"), expected output: [] )
o You will receive 1 pts if your function passes the condition test – the item to be
removed not in the list (e.g., remove_item(["cellphone", "laptop",
"microphone"], "webcam"), expected output: ["cellphone", "laptop",
"microphone"] )
In this task, you will implement a function and no starter code is provided. The function should
be called remove_item and accept two arguments. Given a list of the name of products and the
index of the product to remove from the list, the function should return a list with the product
removed. For example:
>>> remove_item(["cellphone", "laptop", "microphone"], 1)
['cellphone', 'microphone']
The items in the list can be any string and there is no other specifications of the format of the
string.
Submission
Copy the Python code to Lab 9 -> Task 6 on Prairielearn.
You can resubmit your code as many times as you need, but you need to wait for 5 minutes
before submission (You need to spend some time debugging!).
Rubrics:
• You will not receive any mark if you do not submit it to the designated location on
Prairielearn before the deadline
• You will not receive any mark if your code violates the above requirements
• Otherwise
o You will receive 0.25 pts if you provide a description of the function.
o You will receive 0.25 pts if you provide the argument annotations correctly
o You will receive 0.5 pt if you include at least 2 test cases (and they cannot be the
same as test cases provided) and your code pass those test cases
o You will receive 1 pts if your function passes general test (e.g.,
remove_item(["cellphone", "laptop", "microphone"], 1), expected output:
['cellphone', 'microphone'] )
o You will receive 1 pts if your function passes the corner test - zero data (e.g.,
remove_item([], 0), expected output: AssertionError )
o You will receive 1 pts if your function passes the corner test - singleton data
(e.g., remove_item(["laptop"], 0), expected output: [] )
o You will receive 1 pts if your function passes the condition test – the item to be
removed not in the list (e.g., remove_item(["cellphone", "laptop",
"microphone"], 5), expected output: AssertionError )
In this task, you will implement a function and no starter code is provided. The function should
be called remove_item and accept two arguments. Given a tuple of the name of products and
the index of the product to remove from the list, the function should return a tuple with the
product removed. For example:
>>> remove_item(("cellphone", "laptop", "microphone"), 1)
('cellphone', 'microphone')
The items in the tuple can be any string and there is no other specifications of the format of the
string.
Submission
Copy the Python code to Lab 9 -> Task 6 on Prairielearn.
You can resubmit your code as many times as you need, but you need to wait for 5 minutes
before submission (You need to spend some time debugging!).
Rubrics:
• You will not receive any mark if you do not submit it to the designated location on
Prairielearn before the deadline
• You will not receive any mark if your code violates the above requirements
• Otherwise
o You will receive 0.5 pts if you provide a description of the function.
o You will receive 0.5 pts if you provide the argument annotations correctly
o You will receive 1 pt if you include at least 2 test cases (and they cannot be the
same as test cases provided) and your code pass those test cases
o You will receive 2 pts if your function passes general test (e.g.,
remove_item(("cellphone", "laptop", "microphone"), 2), expected output:
['cellphone', ' laptop'] )
o You will receive 2 pts if your function passes the corner test - zero data (e.g.,
remove_item((), 0), expected output: AssertionError )
o You will receive 2 pts if your function passes the corner test - singleton data
(e.g., remove_item(("laptop",), 0), expected output: () )
o You will receive 2 pts if your function passes the condition test – the item to be
removed not in the list (e.g., remove_item(("cellphone", "laptop",
"microphone"), 5), expected output: AssertionError )