2.1 Counting colours
You have an array that stores a list of people’s favourite colours. These colours can appear more than once in the list. Your task is to ask the user to type in a colour they want to check. The program should then go through the array, count how many times that colour appears, and display the total number of matches to the user.
colours = ["blue", "red", "blue", "green", "blue", "red"]
Enter a colour to count: blue The colour blue appears 3 times
set colours to ["blue", "red", "blue", "green", "blue", "red"]
ask user to enter a colour to count and store in target
set count to 0
loop for length of colours array
if colour at current position is equal to target
set count to count + 1
print "The colour", target, "appears", count, "times."
colours = ["blue", "red", "blue", "green", "blue", "red"]
target = input("Enter a colour to count: ")
count = 0
for i in range(len(colours)):
if colours[i] == target:
count = count + 1
print("The colour", target, "appears", count, "times.")
# Array storing favourite colours
colours = ["blue", "red", "blue", "green", "blue", "red"]
# Ask the user for a colour to count
target = input("Enter a colour to count: ")
# Counter starts at 0
count = 0
# Loop through each position in the array
for i in range(len(colours)):
# Check if the colour at current position matches the target
if colours[i] == target:
# If it matches, increase the counter by 1
count = count + 1
# Output the total count
print("The colour", target, "appears", count, "times.")
Extension
Ask the user for a colour, count how many times it appears in the list, and also display the percentage of the list that is that colour.
Enter a colour to count: blue The colour blue appears 3 times. That is 50.0% of the list.