πŸ’ͺ Midterm Practice#

This midterm will assess your mastery of the course content in Weeks 1-4.

Instructions#

You will be provided a link to click to start your midterm at 8 am on Monday, February 5.

Note: For each question, your code should be indented under what is called the function definition: def question_1():. When the autograder is provided, it will help the autograder run all the code you write by calling a single name.

Note: Python cares about Tabs. Make sure spacing is correct in your functions. If you get an Indention Error it likely means your spacing is not correct.

Your solution should look like this:

# DO NOT ALTER lines of code defining the function
def question ():
    line1 = line1_code # line 1 of code
    line2 = line2_code # line 2 of code

    # DO NOT ALTER lines of code in the return statement
    return x, y, z # variables to return separated by commas

Your code replaces the prompt: ...

Part 1: Entering Your Information for Credit#

To receive credit for assignments, it is important we can identify your work from others. To do this, we will ask you to enter your information in the following code block.

Before you begin#

Run the block of code at the top of the notebook that imports and sets up the autograder. This will allow you to check your work.

# Please provide your first name, last name, Drexel ID, and Drexel email. Make sure these are provided as strings. "STRINGS ARE TEXT ENCLOSED IN QUOTATION MARKS."

# In the assignments you will see sections of code that you need to fill in that are marked with ... (three dots). Replace the ... with your code.
first_name = "Person"  
last_name = "Doe"   
drexel_id = "pad123"   
drexel_email = "pad123@drexel.edu"  

Question 1: Identify python objects 8 points

Many kinds of objects exist in python. Among others, we have covered the following objects:

  • list

  • function

  • dictionary

  • float

  • array

  • variable

  • integer

  • string

In the code cell below, write a list that contains in order the exact name that is shown above as a string that corresponds to the description given below.

index 0: a simple human-readable reference to a python object

index 1: a mutable grid of values with th same data type

index 2: a number that has a decimal point

index 3: a series of characters interpreted literally

# define a function called question_1 to be used for grading
def question_1():

    objectNames = ...

    # The following line outputs these values from the function so that they can be accessed by the grader
    return objectNames

Question 2: Create logical statements 9 points

Developing logical statements is essential to coding, especially controlling the flow of a program.

In the code cell below, complete the statements by altering only the ... to ensure that the True or False specified in the comment above the section of code is achieved.

def question_2():

    # complete the statement so that logic1 is True
    a = {'three':3}
    b = 3
    logic1 = (b ... a['three'])

    # complete the statement so that logic2 is False
    c = 8
    d = "8"
    logic2 = (c ... d)
   
    # complete the statement so that logic3 is True
    e = "Drexel"
    f = "drexel"
    logic3 = (e ... f)

    # The following line outputs these values from the function so that they can be accessed by the grader
    return logic1, logic2, logic3

Question 3: Unit conversion with a dictionary 10 points

As an engineer, you will often need to conduct unit conversions. For instance, a value measurement may be in feet that you need in inches or meters.

A dictionary can be an efficient way to store conversion factors and access them for converting values from one unit to another.

Write a function named unit_conversion that uses the dictionary conversion_factors to print the value to two decimal places with the original units and the converted value to two decimal places with the converted units.

For instance, the function should print the following for the test input included below:

10.00 meters is equal to 32.81 feet.

Do not print any other statements or the autograder will not work.

import numpy as np
import warnings

# define a function called unit_conversion to be used for grading
def unit_conversion(value, from_unit, to_unit):
    # Define conversion factors for common units
    conversion_factors = {
        # Length
        'meters': {'meters': 1, 'feet': 3.28084, 'inches': 39.3701, 'centimeters': 100},
        'feet': {'meters': 0.3048, 'feet': 1, 'inches': 12, 'centimeters': 30.48},
        'inches': {'meters': 0.0254, 'feet': 0.0833333, 'inches': 1, 'centimeters': 2.54},
        'centimeters': {'meters': 0.01, 'feet': 0.0328084, 'inches': 0.393701, 'centimeters': 1},
        # Mass
        'kilograms': {'kilograms': 1, 'pounds': 2.20462, 'grams': 1000},
        'pounds': {'kilograms': 0.453592, 'pounds': 1, 'grams': 453.592},
        'grams': {'kilograms': 0.001, 'pounds': 0.00220462, 'grams': 1},
    }

    # Check if the units are in the conversion factors dictionary
    if from_unit in conversion_factors and to_unit in conversion_factors[from_unit]:
    
        # Perform the conversion
        converted_value = ...
        print(...)
    else:
        print("Invalid units for conversion.")
        return warnings.warn("Invalid units for conversion.")

    # The following line outputs the value from the function so that they can be accessed by the grader
    return converted_value

# Check the usage:
value_to_convert = 10
original_unit = 'meters'
target_unit = 'feet'

converted_value = unit_conversion(value_to_convert, original_unit, target_unit)

Question 4: Calculate the vertical component of a force 10 points

Forces are often represented as vectors that can be broken down into horizontal and vertical components. The sine function is used when calculating the vertical component, especially when the force is applied at an angle.

For example, if we have a force F applied at an angle ΞΈ (in degrees) to the horizontal, the vertical component of the force F_vertical can be calculated as:

\[ F_{vertical} = F \cdot \sin(\theta) \]

Write python code to do the following inside the question_4 function below:

  • Define the magnitude of the force, F, as 100 Newtons (with a DataType INT) and the angle, theta, as 78 degrees (with a DataType FLOAT).

  • Convert the angle theta to radians using the math.radians function because the math.sin function expects the angle in radians.

  • Calculate the vertical component of the force, F_vertical, in Newtons.

import numpy as np
import math

# define a function called question_4 to be used for grading
def question_4():

    ...

    # The following line outputs these values from the function so that they can be accessed by the grader
    return F, theta, theta_radians, F_vertical

F, theta, theta_radians, F_vertical = question_4()

Question 5: Using Python as a calculator

We have seen how Python can be used to evaluate mathematical expressions. This problem provides practice incorporating various mathematical functions and constants.

Write python code to do the following:

  • Define variables: a = 3, b = -2, and x = 1

  • For each of the quantities \(E_0\) through \(E_2\), construct a one-line Python expression that computes the value and assigns it to a variable. (You should perform your computations using the variable names \(a\), \(b\), and \(c\) instead of their numerical values). In Python, we will use variable names E0 through E2 to store the values \(E_0\) through \(E_2\). Definitions of the variables E0 through E2 have been started for you in the template.

\(\text{i. } E_0 = ln(4a+b)\)

\(\text{ii. } E_1 = \cos \left( \left( \frac{\pi}{6a} \right)^2 \right)\)

\(\text{i. } E_2 = \sqrt{x^2+a^2+b^2}\)

You should use the NumPy library for the required mathematical functions.

We have used the standard NumPy convention import numpy as np, thus, for example the cos function is used by typing np.cos(<value>)

Again, your code should be indented under the function definition: def question_5():.

Your code replaces the prompt: ...

# import the np library to be used
import numpy as np

# define a function called question_3 to be used for grading
def question_5():

    ...
    
    # output these values from the function so that they can be accessed by the grader
    return a, b, x, E0, E1, E2

Question 6: Analyzing Temperature Distribution Data

In thermal analysis, engineers often deal with temperature distribution across different materials or regions. For example, a mechanical engineer might analyze the temperature distribution across a metal plate, or a civil engineer might be interested in temperature variations across a building’s surface.

You are given a randomly-populated, two-dimensional array representing temperature data, temperature_grid, with a length of 6 in each dimension.

Write Python code to do the following:

  • assign specific_temperature the temperature reading at the second row and fifth column.

  • assign row_temperatures the temperature readings in the fifth row.

  • assign column_temperatures the temperature readings in the second column.

  • assign sub_matrix the temperature readings in a 3 row by 2 column sub-matrix starting from the second row and third column.

Your code should replace this prompt: …

import numpy as np
 
def question_6(seed=None):
    # Set the seed for reproducibility, if provided
    if seed is not None:
        np.random.seed(seed)
 
    ...
 
    return specific_temperature, row_temperatures, column_temperatures, sub_matrix

Submitting Your Assignment#

To submit your assignment, you will use a provided link for GitHub classroom.

Please submit just your output.log file. No other files are needed.

If you need further instructions on submitting your assignment, please ask your TA during lab before the midterm.

Viewing your score#

Each log file you have uploaded will have a file with the name of your file + Grade_Report.md. You can view this file by clicking on the file name. This will show you the results of the autograder.

You will show your grade report to leave the exam room.

Note

In python and particularly jupyter notebooks it is common that during testing you run cells in a different order, or run cells and modify them. This can cause there to be local variables needed for your solution that would not be recreated on running your code again from scratch. Your assignment will be graded based on running your code from scratch. This means before you submit your assignment you should restart the kernel and run all cells. You can do this by clicking Kernel and selecting Restart and Run All. If you code does not run as expected after restarting the kernel and running all cells it means you have an error in your code.

Fin#