Programming Exercises - 004: Lists in Python

Exercises for Understanding Lists in Python with Functions

Below are 20 exercises that make use of Python lists and functions. The expected method signature for each function is provided, making it easier for you to organize your code effectively.

<

Attempt the questions independently. A solution is available on the GitHub page. Simply click to follow.

Exercise 1: Calculate the Total Load

Filename: e01_total_load.py

Write a function that takes a list of loads (in kN) on various points of a beam and calculates the total load on the beam.

For Example: Consider a beam that is carrying loads at different points. The loads act at different points,

 

Loads Applied:

Position (m) Load (kN)
3 10
5 15
7 10
9 5

Expected Output: The total load on the beam: 40 kN. You need to sum the loads to get the total load.

Method Signature: def calculate_total_load(loads: list) -> float:

Hint: Use the sum() function to find the total load.

Illustration:

A beam can be visualised as a bridge across a stream. Assume that loads are people standing at different points. Mathematically, it becomes a graph that probably looks like a histogram with the weight of the person (load) at different points being graphed proportional to their mass.

    title: Beam with Multiple Loads
    showlegend: true
    beam: 0 to 10m
    supports:
    - at 0m (pinned)
    - at 10m (roller)
    loads:
    - at 3m, load: 10 kN
    - at 5m, load: 15 kN
    - at 7m, load: 10 kN
    - at 9m, load: 5 kN
    

This beam spans from 0m to 10m with a pinned support at 0m and a roller support at 10m. The following loads are applied at specific points: - 10 kN at 3m, - 15 kN at 5m, - 10 kN at 7m, - 5 kN at 9m. The beam is analysed for deflection, shear force, and bending moment distributions based on these loads. Analysis, in this case, means determining the deflection values, shear force and bending moment values distributed along the beam.

💡

Trivia: The sum of the forces is an important statics check. The forces act in the direction of gravity. So, if the beam stays in the same place, it is in equilibrium. If we say that gravity acts in a straight line parallel to the 'y' axis, then, the sum of all forces in the 'y' direction is equal to zero will be an equation that is created. The use of this equation will help us find different unknown forces. The computer programs try to generate as many equations as the number of supports required to keep the beam or building in equilibrium.

Exercise 2: Identify Critical Loads

Filename: e02_identify_critical_loads.py

Write a function to identify the critical loads (greater than 50 kN) from a list and store them in a separate list.

For Example: Consider a beam that is carrying several loads, some of which exceed a certain threshold. The loads that exceed 50 kN are considered critical as they may impact the design of the structure significantly.

Loads Applied:

Position (m) Load (kN)
2 20
4 55
6 30
8 60
10 10

Expected Output: The critical loads (those greater than 50 kN) are: [55 kN, 60 kN]. You need to filter the loads that are greater than 50 kN.

Method Signature: def identify_critical_loads(loads: list) -> list:

Hint: Use a list comprehension to filter the loads greater than 50 kN.

Illustration:

    title: Beam with Critical Loads
    showlegend: true
    beam: 0 to 12m
    supports:
    - at 0m (pinned)
    - at 12m (roller)
    loads:
    - at 2m, load: 20 kN
    - at 4m, load: 55 kN
    - at 6m, load: 30 kN
    - at 8m, load: 60 kN
    - at 10m, load: 10 kN
    critical_loads:
    - at 4m, load: 55 kN
    - at 8m, load: 60 kN

This beam spans from 0m to 12m with a pinned support at 0m and a roller support at 12m. Only the loads at 4m and 8m are critical as they exceed 50 kN.

💡

Trivia: The effect of the load is very much dependent on the position of the load. Just like how a 1 kg force can balance one ton of load on a balance simply because of its lever arm, so also, in practice, the load value alone does not cause the loads to be critical.

Exercise 3: Find the Maximum Deflection

Filename: e03_max_deflection.py

Write a function to find the maximum deflection from a list of deflection values at different points along a beam.

For Example: Consider a beam that is experiencing deflection at various points due to loads. The deflection values indicate how much the beam bends at specific locations. Your task is to determine the maximum deflection value, which corresponds to the point where the beam bends the most.

Deflections at Different Points:

Position (m) Deflection (mm)
0 0
2 -10
4 -20
6 -25
8 -15
10 0

Expected Output: The maximum deflection is -25 mm at 6 meters. Use the max() function to find the maximum deflection.

Method Signature: def find_max_deflection(deflections: list) -> float:

Hint: Use the max() function to find the maximum deflection.

Illustration:

    title: Beam with Deflection Values
    showlegend: true
    beam: 0 to 10m
    supports:
    - at 0m (pinned)
    - at 10m (roller)
    deflection:
    - at 0m, deflection: 0
    - at 2m, deflection: -10
    - at 4m, deflection: -20
    - at 6m, deflection: -25
    - at 8m, deflection: -15
    - at 10m, deflection: 0

This beam has a maximum deflection of -25 at 6m, which represents the point where the beam got displaced the most due to the application of loads.

💡

Trivia: The forces that act on a beam cause the beam to sag. The distance of a point on the beam after applying a load from the original position is deflection.

Exercise 4: Reverse the Order of Survey Points

Filename: e04_reverse_survey_points.py

Write a function to reverse the order of survey points recorded along a path. The function should return the list of points with their order reversed.

Method Signature: def reverse_survey_points(points: list) -> list:

Hint: Use list slicing to reverse the order of elements in the list (points[::-1]).

Survey Points and Elevations:

Station Distance (m) Elevation (m)
A 0 0
B 50 5
C 100 10
D 150 8
E 200 3

Expected Output: The points should be returned in reversed order. For example, if the original list is from 0m to 200m, the reversed output will be:

In this example, the original survey points are reversed, so the point at 200m now appears first, and the point at 0m appears last.

Working with Lists of Lists (Coordinates): If the points are represented as a list of lists, where each inner list is a pair of coordinates, such as:

points = [[0, 0], [50, 5], [100, 10], [150, 8], [200, 3]]

You can reverse this list using slicing:

reversed_points = points[::-1]

This will give:

[[200, 3], [150, 8], [100, 10], [50, 5], [0, 0]]

Now the coordinates are reversed.

Illustration:

        survey_type: traverse
        title: Survey Points Before Reversal
        showlegend: true
        xaxislabel: Distance (m)
        yaxislabel: Elevation (m)
        - at (0, 0), elevation: 0, station: A
        - at (50, 50), elevation: 5, station: B
        - at (100, 100), elevation: 10, station: C
        - at (150, 150), elevation: 8, station: D
        - at (200, 200), elevation: 3, station: E
    

Reversed Order (Modified List):

Station Distance (m) Elevation (m)
E 200 3
D 150 8
C 100 10
B 50 5
A 0 0

Reversed Order:

        survey_type: traverse
        title: Survey Points After Reversal
        showlegend: true
        xaxislabel: Distance (m)
        yaxislabel: Elevation (m)
        - at (200, 200), elevation: 3, station: E
        - at (150, 150), elevation: 8, station: D
        - at (100, 100), elevation: 10, station: C
        - at (50, 50), elevation: 5, station: B
        - at (0, 0), elevation: 0, station: A
    
💡

Trivia: Each survey point has an associated elevation value, but for this exercise, we are only interested in reversing the order of the survey points based on their distance along the path. Elevation values are maintained in the reversed list but are not used for any computations in this task.

Exercise 5: Find All Points Within a Given Range

Filename: e05_points_in_range.py

Write a function to find all survey points that lie within a given range (e.g., between 100 m and 200 m). The function should return a list of points that fall within the specified distance range.

Method Signature: def find_points_in_range(points: list, start: float, end: float) -> list:

Hint: Use a for loop to iterate through the list and check if the values fall within the range.

Survey Points and Elevations:

Station Distance (m) Elevation (m)
A 0 0
B 50 5
C 100 10
D 150 8
E 200 3
F 250 5
G 300 0

Expected Output: The points that fall within the range of 100m to 200m should be returned. For example, if the range is from 100m to 200m, the output will be:

Working with Lists of Lists (Coordinates): If the points are represented as a list of lists, where each inner list is a pair of coordinates, such as:

points = [[0, 0], [50, 5], [100, 10], [150, 8], [200, 3], [250, 5], [300, 0]]

Illustration:

        survey_type: traverse
        title: Survey Points with Range Filter
        showlegend: true
        xaxislabel: Distance (m)
        yaxislabel: Elevation (m)
        - at (0, 0), elevation: 0, station: A
        - at (50, 50), elevation: 5, station: B
        - at (100, 100), elevation: 10, station: C
        - at (150, 150), elevation: 8, station: D
        - at (200, 200), elevation: 3, station: E
        - at (250, 250), elevation: 5, station: F
        - at (300, 300), elevation: 0, station: G
    

You can filter these points to find only those within a given range:

filtered_points = [point for point in points if 100 <= point[0] <= 200]

This will give:

[[100, 10], [150, 8], [200, 3]]

Now, the filtered list only contains the points within the specified distance range.

Filtered Points (100m to 200m):

Station Distance (m) Elevation (m)
C 100 10
D 150 8
E 200 3

Filtered Points (100m to 200m):

        survey_type: traverse
        title: Points Within 100m to 200m
        showlegend: true
        xaxislabel: Distance (m)
        yaxislabel: Elevation (m)
        - at (100, 100), elevation: 10, station: C
        - at (150, 150), elevation: 8, station: D
        - at (200, 200), elevation: 3, station: E
    
💡

Trivia: Although the survey points have an associated elevation value, for this task, we are only concerned with the distances and not the elevation data. However, elevation information can be crucial in other analyses, such as determining slopes or changes in terrain.

Exercise 6: Average Soil Test Results

Filename: e06_average_soil_test.py

Write a function to calculate the average value of soil test results from a given list.

Method Signature: def calculate_average_soil_test(results: list) -> float:

Hint: Use the sum() function along with len() to calculate the average.

Exercise 7: Remove Duplicate Load Cases

Filename: e07_remove_duplicates.py

Write a function to remove duplicate load cases from a list of load values.

Method Signature: def remove_duplicates(loads: list) -> list:

Hint: Convert the list to a set to remove duplicates and then back to a list to retain the original structure.

Exercise 8: Insert Missing Data at Specific Positions

Filename: e08_insert_missing_data.py

Write a function to insert missing data points (represented by None) at specific positions in a list of survey data.

Method Signature: def insert_missing_data(data: list, positions: list) -> list:

Hint: Use the insert() method to add None at the specified positions.

Exercise 9: Compare Loads Before and After an Event

Filename: e09_compare_loads.py

Write a function that takes two lists representing loads before and after a specific event. Find the difference in loads at each point and store it in a new list.

Method Signature: def compare_loads(before: list, after: list) -> list:

Hint: Use a for loop or list comprehension with the zip() function.

Exercise 10: Sort Load Values

Filename: e10_sort_load_values.py

Write a function to sort a list of load values in ascending order.

Method Signature: def sort_load_values(loads: list) -> list:

Hint: Use the sorted() function or the sort() method.

Exercise 11: Extract Even-Indexed Survey Points

Filename: e11_even_indexed_points.py

Write a function that extracts survey points from even-indexed positions in a list of data points.

Method Signature: def extract_even_indexed_points(points: list) -> list:

Hint: Use list slicing with a step of 2.

Exercise 12: Calculate Cumulative Load

Filename: e12_cumulative_load.py

Write a function to calculate the cumulative load at each point along a beam, given a list of load values.

Method Signature: def calculate_cumulative_load(loads: list) -> list:

Hint: Use a loop to add each load to a cumulative total and store the result in a new list.

Exercise 13: Find Deflection Beyond a Threshold

Filename: e13_deflection_threshold.py

Write a function that finds all deflection values greater than a specified threshold (e.g., 10 mm) and prints their indices.

Method Signature: def find_deflection_above_threshold(deflections: list, threshold: float) -> list:

Hint: Use enumerate() to get both the index and the value while iterating.

Exercise 14: Group Load Values by Type

Filename: e14_group_load_values.py

Write a function to group load values into two categories: point loads and super point loads. Assume point loads are below 10 kN, while super point loads are 10 kN or above.

Method Signature: def group_load_values(loads: list) -> tuple:

Hint: Use two separate lists and a loop to append values to the appropriate list based on the condition.

Exercise 15: Replace Outliers in Soil Test Data

Filename: e15_replace_outliers.py

Write a function to replace outliers in a list of soil test data (values greater than 100) with the average value of the list.

Method Signature: def replace_outliers(data: list) -> list:

Hint: Use a loop and conditional statements to find outliers, then replace them.

Exercise 16: Merge Two Sets of Survey Data

Filename: e16_merge_survey_data.py

Write a function to merge two lists of survey data into one, removing any duplicate values.

Method Signature: def merge_survey_data(data1: list, data2: list) -> list:

Hint: Use set() to remove duplicates and list() to convert it back.

Exercise 17: Find Common Load Cases

Filename: e17_common_load_cases.py

Write a function to find common load cases between two different lists of load values.

Method Signature: def find_common_loads(loads1: list, loads2: list) -> list:

Hint: Use set intersection to find common elements between two lists.

Exercise 18: Divide Load Values by a Safety Factor

Filename: e18_divide_by_safety_factor.py

Write a function to divide each load value in a list by a safety factor (e.g., 1.5) and store the safe load values in a new list.

Method Signature: def divide_loads_by_safety_factor(loads: list, safety_factor: float) -> list:

Hint: Use a list comprehension to apply the safety factor to each value in the list.

Exercise 19: Count the Number of Zero Loads

Filename: e19_count_zero_loads.py

Write a function to count the number of zero loads in a list of load values.

Method Signature: def count_zero_loads(loads: list) -> int:

Hint: Use the count() method to find the occurrences of zero.

Exercise 20: Detect Change in Deflection

Filename: e20_detect_deflection_change.py

Write a function that detects if there is a sudden change in deflection values along a beam (e.g., a difference greater than 5 mm between two consecutive points).

Method Signature: def detect_deflection_change(deflections: list, threshold: float) -> list:

Hint: Use a loop to compare the difference between each consecutive pair of deflection values.

Key Takeaways

These exercises will help you understand the versatility of Python lists and how they can be used in various practical scenarios involving engineering data. Practice these exercises to strengthen your understanding of list operations and prepare for more complex applications.