Code

Score a Possible Message

Time to teach the computer to "read". We'll give each candidate a score: one point for every word that appears in a list of common words. Gibberish scores 0. Real messages score high.

words = ["the", "is", "map"]
text = "The map is here!"
for word in text.lower().split():
    print(word.strip(".,!?"))
  • .lower() makes The match the.
  • .split() chops the text into words at the spaces.
  • .strip(".,!?") peels punctuation off the ends, so here! becomes here.

Then pick the candidate with the highest score. If two candidates tie, keep the one that came first. That way the program always gives the same answer.

Assignment

  1. score(text, words) returns how many words in text are in the list words. Repeats count each time: score("the the", ["the"]) is 2.
  2. best_guess(candidates, words) returns the candidate with the highest score, using score. On a tie, return the earlier one.