Scenario: A small fleet of delivery vans stores distances in a 2D array. Each row is a van and each column is a day: Monday, Wednesday and Friday (kilometres).
Data
delivery_distances = [
# Mon, Wed, Fri
[120, 85, 150], # Van 1
[95, 110, 95], # Van 2
[145, 130, 160], # Van 3
[80, 75, 90] # Van 4
]
Your tasks
- Counting — count how many daily trips in the whole fleet were 100 km or longer.
- Totalling — calculate and print the total distance traveled by Van 2 (row index 1).
- Averaging — calculate the average delivery distance on Wednesday (column index 1).
- Maximum and minimum — find the longest single trip on Friday (column 2) and the shortest single trip on Monday (column 0).
💡 Try every task in your editor first. Only reveal the solution when you have had a proper go.
Solution
delivery_distances = [
[120, 85, 150],
[95, 110, 95],
[145, 130, 160],
[80, 75, 90]
]
# Question 1: Counting
count = 0
for row in delivery_distances:
for distance in row:
if distance >= 100:
count = count + 1
print("Trips of 100 km or longer:", count)
# Question 2: Van 2 total
van2_total = 0
for distance in delivery_distances[1]:
van2_total = van2_total + distance
print("Van 2 total distance:", van2_total)
# Question 3: Wednesday average (column 1)
wednesday_total = 0
for r in range(len(delivery_distances)):
wednesday_total = wednesday_total + delivery_distances[r][1]
wednesday_average = wednesday_total / len(delivery_distances)
print("Wednesday average:", wednesday_average)
# Question 4: Max Friday, min Monday
max_friday = delivery_distances[0][2]
min_monday = delivery_distances[0][0]
for r in range(len(delivery_distances)):
if delivery_distances[r][2] > max_friday:
max_friday = delivery_distances[r][2]
if delivery_distances[r][0] < min_monday:
min_monday = delivery_distances[r][0]
print("Longest Friday trip:", max_friday)
print("Shortest Monday trip:", min_monday)
Example output:
Trips of 100 km or longer: 6
Van 2 total distance: 300
Wednesday average: 100.0
Longest Friday trip: 160
Shortest Monday trip: 80