4.3 Name length

You are given two parallel arrays:

  • forenames – stores the first names of pupils
  • surnames – stores the surnames of pupils

Your task is to calculate the average length of the surnames (in characters).
Then use a linear search through the arrays to display the full name (forename + surname) of every pupil whose surname is longer than the average length.

forenames = ["Ava", "Ben", "Liam", "Mia", "Zoe"]
surnames = ["Lee", "Smith", "O’Connor", "Patel", "Thompson"]

 

Average surname length: 5.8
Longer-than-average surnames:
Liam O’Connor
Zoe Thompson
set forenames to ["Ava", "Ben", "Liam", "Mia", "Zoe"]
set surnames  to ["Lee", "Smith", "O’Connor", "Patel", "Thompson"]

total = 0

calculate average surname length

display "Average surname length: ", average
display "Longer-than-average surnames:"

set found to False

for position from 0 to last surname
    if length of surnames[position] > average then
        display forenames[position] + " " + surnames[position]
        set found to True

 

forenames = ["Ava", "Ben", "Liam", "Mia", "Zoe"]
surnames  = ["Lee", "Smith", "O’Connor", "Patel", "Thompson"]

total = 0
for i in range(len(surnames)):
    total = total + len(surnames[i])

average = total / len(surnames)

print("Average surname length:", average)
print("Longer-than-average surnames:")

found = False
for i in range(len(surnames)):
    if len(surnames[i]) > average:
        print(forenames[i] + " " + surnames[i])
        found = True
# Parallel arrays of equal length
forenames = ["Ava", "Ben", "Liam", "Mia", "Zoe"]
surnames  = ["Lee", "Smith", "O’Connor", "Patel", "Thompson"]

# Step 1: Calculate the average surname length
total = 0
for i in range(len(surnames)):
    # Add the length of each surname to the running total
    total = total + len(surnames[i])

# Divide total length by number of surnames to get the average
average = total / len(surnames)

# Show the average
print("Average surname length:", average)
print("Longer-than-average surnames:")

# Step 2: Use linear search to find longer surnames
found = False
for i in range(len(surnames)):
    # If surname length is greater than the average
    if len(surnames[i]) > average:
        # Print the full name (forename + space + surname)
        print(forenames[i] + " " + surnames[i])
        found = True

Extension

Update the program to not only display the pupils with surnames longer than the average, but also show how many characters longer than the average each surname is.

Average surname length: 5.8
Longer-than-average surnames (with difference):
Liam O’Connor — 2.2 above average
Zoe Thompson — 2.2 above average