12.2 - Oldest person

Problem

The file people.csv stores the names and ages of 100 people.
(DOWNLOAD IN STUDY KIT)

Hugo,44
Madison,50
Phoebe,73
...

Write a program that will

  • Read the names and ages into parallel arrays
  • Find and display the name of the oldest person.

Example run

Thomas is the oldest person at 79 years old.

 

1 Read data into parallel arrays IN
OUT names, ages
2 Find and display the name of the oldest person IN names, ages
OUT
1.1 Create a names array of 100 strings
1.2 Create a ages array of 100 integers
1.3 Open people.csv file
1.4 For i from 0 to 99
1.5     set names[i] and ages[i] to next line of file
1.6     set ages[i] to int(ages[i])
1.7 End for
1.8 Close file
1.9 return names, ages

 

# Main
names, ages = read_data()
find_oldest(names, ages)
def read_data():
    names = [str] * 100
    ages = [int] * 100
    file = open("people.csv", "r")
    for i in range(100):
        names[i], ages[i] = file.readline().strip().split(",")
        ages[i] = int(ages[i])
    file.close()
    return names, ages

def find_oldest(names, ages):
    oldest_pos = 0
    for i in range(len(ages)):
        if ages[i] > ages[oldest_pos]:
            oldest_pos = i
    print(names[oldest_pos], "is the oldest person at", ages[oldest_pos], "years old.")

# Main
names, ages = read_data()
find_oldest(names, ages)
# read_data
# Reads 100 lines from a CSV file named "people.csv".
# Each line contains a name and an age separated by a comma (e.g. "Alice,14").
# open("people.csv", "r") – opens the file for reading.
# readline() – reads one line from the file each time.
# strip() – removes the hidden newline (\n) at the end of each line.
# split(",") – splits the line into two parts: name and age.
# int() – converts the age from a string to an integer.
# close() – closes the file when reading is finished.
def read_data():
    names = [str] * 100
    ages = [int] * 100
    file = open("people.csv", "r")
    for i in range(100):
        names[i], ages[i] = file.readline().strip().split(",")
        ages[i] = int(ages[i])
    file.close()
    return names, ages

# find_oldest
# Finds the oldest person by comparing ages in the array.
# Starts by assuming the first person is the oldest.
# Loops through each age and updates the position when a higher value is found.
# Displays the name and age of the oldest person.
def find_oldest(names, ages):
    oldest_pos = 0
    for i in range(len(ages)):
        if ages[i] > ages[oldest_pos]:
            oldest_pos = i
    print(names[oldest_pos], "is the oldest person at", ages[oldest_pos], "years old.")

# Main
# Calls read_data() to get names and ages from the file.
# Then calls find_oldest() to find and display the oldest person.
names, ages = read_data()
find_oldest(names, ages)

Extension

Update the program to write the answer to a text file.

Target

Read data from file to parallel arrays

Study Kit