12.1 - Favourite day

Problem

A questionnaire asked 100 people which day of the week was their favourite.

The results of the questionnaire are stored in the file days.txt (DOWNLOAD IN STUDY KIT)

Write a program that will count and display how many people chose Monday as their favourite day.

Example run

21 people choose Monday as their favourite day.

 

1 Read data into days array IN  
OUT days
2 Count and display the number of Mondays IN days
OUT  
1.1 Create a days array of 100 strings
1.2 Open days.txt file
1.3 For i from 0 to 99
1.4     set days[i] to next line of file
1.5 End for
1.6 Close file
1.5 return days

 

# Main
days = read_data()
count_mondays(days)
def read_data():
    days = [str] * 100
    file = open("days.txt", "r")
    for i in range(100):
        days[i] = file.readline().strip()
    file.close()
    return days

def count_mondays(days):
    count = 0
    for i in range(len(days)):
        if days[i] == "Monday":
            count = count + 1
    print(count, "people choose Monday.")

# Main
days = read_data()
count_mondays(days)
# read_data
# Reads 100 lines from a text file and stores them in an array.
# open("days.txt", "r")   → Opens the file for reading.
# readline()              → Reads one line from the file each time it is called.
# strip()                 → Removes the newline (\n) at the end of each line.
# close()                 → Closes the file once all data has been read.
def read_data():
    days = [str] * 100
    file = open("days.txt", "r")
    for i in range(100):
        days[i] = file.readline().strip()
    file.close()
    return days

def count_mondays(days):
    count = 0
    for i in range(len(days)):
        if days[i] == "Monday":
            count = count + 1
    print(count, "people choose Monday.")

# Main
days = read_data()
count_mondays(days)

Extension

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

Target

Read data from file to an array

Study Kit