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.


Pages: 1 2

3 Responses to “Favorite Color”

  1. Or you can do it in perl…

    perl -e '$x{$_}++ foreach map {m{favoritecolor: (.*)} ? $1 : ()} <>; print [sort {$x{$a} <=> $x{$b}} keys %x ]->[-1],"\n";' file.txt
  2. Jussi Piitulainen said

    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

  3. Mike said

    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.

    from collections import Counter
    import re
    match = re.compile(r'favoritecolor: .+').match
    with open('./testdb.txt', 'rt') as f:
        Counter(filter(match, f)).most_common()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: