50 XP

51. Word pattern

Intermediate dictionaries strings

A pattern like "abba" describes a sentence whose first and last words are the same, and whose two middle words are the same as each other but different from the first. "dog cat cat dog" follows it; "dog cat cat fish" doesn't.

Write a function follows_pattern(pattern, sentence) that takes a pattern of letters and a sentence of words, and returns True if the sentence follows the pattern, or False if it doesn't. It follows the pattern when:

  • it has exactly as many words as the pattern has letters, and
  • each letter always stands for the same word, and
  • each word always stands for the same letter: two different letters can't stand for the same word.

The last rule is why "ab" and "dog dog" don't match, even though each letter keeps to one word.

Example 1

Inputpattern = "abba", sentence = "dog cat cat dog"
OutputTrue
Explanationa is always dog, b is always cat.

Example 2

Inputpattern = "abba", sentence = "dog cat cat fish"
OutputFalse
Explanationa is dog at the start but fish at the end.

Example 3

Inputpattern = "ab", sentence = "dog dog"
OutputFalse
Explanationa and b would both stand for dog.

Constraints

  • pattern has 1 to 20 lower-case letters.
  • sentence has 1 to 20 words of lower-case letters, separated by single spaces.

Submit also runs 9 more tests you can't see.

Practises Dictionaries (lesson 11).

Code
def follows_pattern(pattern, sentence):
    """Check whether a sentence follows a letter pattern.

    pattern: str, lower-case letters
    sentence: str, words separated by spaces
    Returns: bool, True if letters and words match one to
        one, else False
    """
    # Write your code here
    pass