51. Word pattern
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
pattern = "abba", sentence = "dog cat cat dog"TrueExample 2
pattern = "abba", sentence = "dog cat cat fish"FalseExample 3
pattern = "ab", sentence = "dog dog"FalseConstraints
patternhas 1 to 20 lower-case letters.sentencehas 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).
sentence.split()gives the list of words. If its length differs fromlen(pattern), the answer isFalsestraight away.zip(pattern, words)walks through each letter and its word together. A dictionary from letter to word catches a letter that changes its word.- One dictionary isn't enough:
"ab"with"dog dog"passes it. Keep a second one from word to letter, and check both for every pair.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.