# You must make sure to run all cells in sequence using shift + enter or you might encounter errors
from pykubegrader.initialize import initialize_assignment
responses = initialize_assignment("1_practicemidterm_q", "week_6", "practicemidterm", assignment_points = 225.0, assignment_tag = 'week6-practicemidterm')
# Initialize Otter
import otter
grader = otter.Notebook("1_practicemidterm_q.ipynb")
โ ENGR131: Introduction to Programming for Engineers#
Practice Midterm Exam#
The practice midterm is designed to help you prepare for the actual midterm exam. It is designed to be similar in format and difficulty to the actual exam. The practice exam is graded and counts as 10% bonus points towards your midterm exam grade.
For the multiple choice questions it is expected that you have access to a python interpreter. Do not go at it alone, use the resources available to you to help you answer the questions. Without the interpreter some of the questions may be difficult to answer.
# Run this block of code by pressing Shift + Enter to display the question
from questions._1_practicemidterm_q import Question1
Question1().show()
# Run this block of code by pressing Shift + Enter to display the question
from questions._1_practicemidterm_q import Question2
Question2().show()
# Run this block of code by pressing Shift + Enter to display the question
from questions._1_practicemidterm_q import Question3
Question3().show()
Question 1 (Points: 22.0): Engineering Component Tracker: Loops, Continue, Break, Dictionaries, and Lists#
Instructions:#
You are managing the assembly of a robotic arm. Each component of the arm is represented as a dictionary, where the keys are component IDs (e.g., โA1โ) and the values are dictionaries containing component details. Your task is to write a function process_components()
that processes a list of components using loops, continue
, and break
.
Requirements:#
Input: The function receives a list of dictionaries, each representing a component:
| id | status | weight | |-----|--------|--------| | A1 | ok | 3.5 | | B2 | ok | 2.0 | | C3 | error | 4.1 | | D4 | ok | 1.2 |
Part 1: Count the components with status โokโ using a loop and return the count.
Part 2: Skip components with status โerrorโ, and create a list of IDs for valid components.
Part 3: If a componentโs weight exceeds 4.0, break the loop and return โOverweight component detected!โ.
Part 4: Return a dictionary summarizing the count of โokโ components, the valid IDs list, and the break message (if triggered).
Helpful Information:#
Use a loop to iterate through the
components
list.Use
continue
to skip certain iterations based on a condition.Use
break
to exit the loop early when another condition is met.Remember that you can access dictionary values using the syntax
dictionary[key]
.Example methods:
append
: Add an element to a list.
We provide detailed inline instructions for each part of the task. Please read the instructions carefully and complete each part accordingly.
# write the components list of dictionaries based on the table provided, assign it to a variable `components`
...
# define a function `process_components` that takes a dictionary of components as input
...
# Initialize variables
# create a variable `ok_count` and set it to 0
# create a variable `valid_ids` and set it to an empty list
# create a variable `break_message` and set it to None
...
# Loop through components
...
# Part 3: Check for overweight components
# if the component's weight is greater than 4.0, set `break_message` to "Overweight component detected!" and break the loop
...
# Part 2: Skip components with status "error"
# if the component's status is "error", continue to the next iteration
...
# Part 1: Count components with status "ok"
# if the component's status is "ok", increment `ok_count` by 1 and append the component's id to `valid_ids`
...
# Part 4: Return the results as a dictionary
# return a dictionary with keys "ok_count", "valid_ids", and "break_message" and their corresponding values
...
# Call the function with the components dictionary and store the result in a variable `result`
# You can print the results function to check if it's working correctly
...
grader.check("loops-and-dictionaries-engineering")
Question 2 (Points: 16.0): Symbolic Computation with SymPy#
Instructions:#
Using SymPy, a package for symbolic solving in Python. Your task is to define and visualize an equation symbolically.
Requirements:#
Part 1: Define symbolic variables ( x ) and ( y ).
Part 2: Construct the equation:
Part 3: Use
sympy.plot_implicit
to visualize the shape. We do not expect you to know how to use this function. You should use one of the several methods shown in class to read the docstring.Part 4: Return the equation and the plot object.
Helpful Information:#
Make sure you import from
sympy
symbols
,Eq
, and fromsympy.plotting
plot_implicit
.Use
symbols
from SymPy to define ( x ) and ( y ).Use
Eq
to represent the equation.Use
plot_implicit
to visualize the shape.
# Import required functions from sympy
...
# Define symbolic variables
...
# Construct the shape equation
# save to the variable eq
...
# Plot the equation
# x and y limits should be between -1.5 and 1.5
# The syntax for plot_implicit is plot_implicit(equation, (x, x_min, x_max), (y, y_min, y_max))
# save the plot to the variable plot
...
# do not modify below this line
# this is used for grading
def get_equation():
return eq, plot
plot.show()
grader.check("symbolic-heart-curve")
Question 3 (Points: 14.0): Debugging Python Functions: Syntax, Runtime, and Semantic Errors#
Instructions:#
You are provided with the following code which is full of bugs. Your task is to debug the code and fix all the errors. The function square_positive_numbers
is intended to take a list of numbers as input and return a new list where each positive number is squared, the negative numbers are excluded.
def square_positive_numbers(numbers):
new_list = []
for num in numbers:
if num =< 0
continue
newLsit.append(num ** 2)
print(new_list)
# Example usage:
numbers = [1, -2, 3, -4, 5]
print(square_positive_numbers(numbers)) # This should print [1, 9, 25]
Requirements:#
Input: The function receives a list of numbers.
Expected Behavior: The function should return a new list where each number is squared, but only if it is positive.
Possible Errors to Fix:
Syntax Errors (incorrect operators, missing colons, indentation issues).
Runtime Errors (incorrect function calls, undefined variables).
Semantic Errors (logical mistakes affecting correct behavior).
Return Value: The function should return the transformed list, not just print it.
# Define a function `square_positive_numbers` that takes a list of numbers as input
...
numbers = [1, -2, 3, -4, 5]
result = square_positive_numbers(numbers)
print(result)
grader.check("loops-and-errors-debugging")
Question 4 (Points: 25.0): Numerical Computing with NumPy: Prime Number Checker ๐ข#
Instructions:#
You are working with numerical data and need to determine which numbers in a given NumPy array are prime. Your task is to write a function find_primes()
that takes a NumPy array of integers and returns a boolean array indicating which elements are prime.
Requirements:#
The function receives a NumPy array of positive integers, or a list of positive integers.
Implement an efficient prime-checking function using NumPy.
The function should return a boolean NumPy array of the same shape as the input, where
True
represents a prime number andFalse
represents a non-prime.
Helpful Information:#
A prime number is a natural number greater than 1 that has only two divisors: 1 and itself.
The first few primes are: 2, 3, 5, 7, 11, 13, โฆ
The function should handle edge cases like
0
and1
correctly (they are not prime).
We have provided inline instructions for each part of the task. Please read the instructions carefully and complete each part accordingly.
Make sure to include docstring and comments in your code to explain the logic and purpose of the function.
# import numpy use the common alias np
...
# Define the function `find_primes` which accepts and input arr
...
"""
...
"""
# Ensure input is a NumPy array, to do this convert the input to a NumPy array using `np.asarray`
# Override the input variable `arr` with the NumPy array
...
# Initialize a boolean array `is_prime` with the same shape as the input array
# Set all values to `True` initially, this generally happens by default with ones_like
# You can use the `np.ones_like` function to initialize the array, make sure to set the `dtype` to `bool`
...
# Mark 0 and 1 as non-prime
# Use indexing to set the values at indices less than 2 to `False`
# hint, you need to build a boolean array that can index is_prime that finds all values in the array that are less than 2
...
# The trick to finding primes is to mark multiples of each number as non-prime
# Loop through numbers starting from 2 up to the square root of the maximum number in the array -- make sure to use the NumPy function which supports arrays
# If you use the max() function it will not work for multidiemensional arrays that cannot be converted to a list inside python.
# Use the `np.sqrt` function to calculate the square root
# Use the `int` function to convert the result to an integer -- make sure to add 1 to the result
# Use the `range` function to loop through the numbers
# Write your for loop here
...
# Create a boolean mask to identify multiples of the current number
# These are the numbers that are divisible by the current number but not equal to the current number
# You will want to use the `&`` operator which conducts an element-wise AND operation on two boolean arrays, or tuples.
# Save the mask to a variable `mask`
...
# Mark multiples as non-prime by setting the corresponding values in `is_prime` to `False`
...
# Return the boolean array `is_prime`
...
# Example usage:
test_array = np.array([0, 1, 2, 3, 4, 5, 10, 11, 13, 15, 17])
prime_results = find_primes(test_array)
print(prime_results)
grader.check("numpy-prime-check")
Question 5 (Points: 24.0): String Processing with Sliding Window: Longest Unique Substring ๐ #
Instructions:#
You are given a string s
containing lowercase and uppercase English letters, digits, and special characters. Your task is to implement a function length_of_longest_substring()
that returns the length of the longest substring without repeating characters.
This question is designed to test your understanding of algorithmic thinking. You can solve this problem using any approach you prefer, but we recommend using the sliding window technique for efficiency.
Requirements:#
Input: The function receives a string
s
.Ensure that the function correctly tracks character positions to prevent repetition.
Return an integer representing the maximum length of a substring without repeating characters.
Helpful Information:#
A substring is a contiguous sequence of characters within a string.
You should might want to use a dictionary to store the last seen index of characters.
Use the sliding window approach to efficiently check substrings.
Ideally the function should work well for very large strings.
Viable logic#
Define a dictionary to store the last seen index of characters. The key is the character, and the value is the index.
Store the max length of all substrings found so far.
Store the start index, the left pointer of a window in the string.
Iterate through the string, it is helpful to use the enumerate function to get the index and character.
If the character is in the dictionary, and the characterโs index is greater than or equal to the start index, update the start index to the characterโs index + 1.
Update the characterโs index in the dictionary, to the last seen index.
Use the max function to update the max length of all substrings found so far, this is either the current max value, or the length of the current substring. Make sure you think about the edge case where the substring is the entire string, and how python indexing works.
Return the max length of all substrings after traversing the string.
The goal is to go through character by character, and keep track of the last seen index of each character. If a character is repeated then move the left pointer to the right by one so there are no repeating characters in the substring. If the distance between the left pointer and the current character is greater than the current max length, update the max length.
# define your function `length_of_longest_substring`
...
# Example usage:
test_string = "abcabcbb"
result = length_of_longest_substring(test_string)
print(result) # Expected output: 3
grader.check("longest-unique-substring")
Question 6 (Points: 60.0): Bonus Question: Cracking Agarโs Password to Uncover a Secret Message ๐ต๏ธโโ๏ธ#
Note: This question is optional. You can choose to attempt this question if you want to earn bonus points. This question is designed to test your problem-solving skills and creativity โ it is well above the difficulty level of the regular questions and is not within the scope of the exam content. This is for students that are looking for an extra challenge.
Instructions:#
You have intercepted a message from Agar, concealing a deep dark secret about a former life as a pop star - at least of the background vocal kind. You know the message encrypted_message.txt
is encrypted using a simple XOR cipher, but you donโt know the key. Your task is to write a function crack_agar_password()
that decrypts the message and reveals the secret. You were able to watch Professor Agar in class as he typed in his password, you saw that the password was a series of letters - which you assume is a word in the english language - all of which are provided in words.txt
, a single number, and a special character [!@#$%^&*()_+].
You make some good assumptions that the message is in English, and that the message might contain a link to a website.
...
...
# Run the function
password = crack_agar_password()
grader.check("Bonus-Question-Cracking the Code")
Submitting Assignment#
Please run the following block of code using shift + enter
to submit your assignment, you should see your score.
from pykubegrader.submit.submit_assignment import submit_assignment
submit_assignment("week6-practicemidterm", "1_practicemidterm_q")