Favorite Color
November 11, 2014
A text file consists of records with fields. Each field is a name/value record of the form name: value
with the field name followed by a colon, a space, and the value. Records consist of one or more fields separated by a blank line. In a particular database one field is named favoritecolor
.
Your task is to write a program that determines the maximal favorite color; in other words, what color is named the most times as the favorite color. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Or you can do it in perl…
Nah. I thought of Awk, and I thought of Python’s Counter objects, but this is what I would actually do, including the output of more than one line, to see if there is a tie or a near tie.
$ grep -E '^favoritecolor:' particular.txt | cut -d ' ' -f 2 | sort | uniq -c | sort -nr | head
Unfortunately, my UNIX command line is so rusty, I’d use Python.
Assumes one name/value pair per line in the file (problem doesn’t specify). Didn’t bother splitting the name/value pair, because it doesn’t change the counts. Outputs a sorted list of all the colors and their counts.