MCPcopy
hub / github.com/keon/algorithms / word_pattern

Function word_pattern

algorithms/map/word_pattern.py:17–47  ·  view source on GitHub ↗

Check if a string follows the given pattern. Args: pattern: A pattern string of lowercase letters. string: A space-separated string of words. Returns: True if the string follows the pattern, False otherwise. Examples: >>> word_pattern("abba", "dog cat c

(pattern: str, string: str)

Source from the content-addressed store, hash-verified

15
16
17def word_pattern(pattern: str, string: str) -> bool:
18 """Check if a string follows the given pattern.
19
20 Args:
21 pattern: A pattern string of lowercase letters.
22 string: A space-separated string of words.
23
24 Returns:
25 True if the string follows the pattern, False otherwise.
26
27 Examples:
28 >>> word_pattern("abba", "dog cat cat dog")
29 True
30 >>> word_pattern("abba", "dog cat cat fish")
31 False
32 """
33 mapping: dict[str, str] = {}
34 mapped_values: set[str] = set()
35 words = string.split()
36 if len(words) != len(pattern):
37 return False
38 for i in range(len(pattern)):
39 if pattern[i] not in mapping:
40 if words[i] in mapped_values:
41 return False
42 mapping[pattern[i]] = words[i]
43 mapped_values.add(words[i])
44 else:
45 if mapping[pattern[i]] != words[i]:
46 return False
47 return True

Callers 1

test_word_patternMethod · 0.90

Calls 1

addMethod · 0.80

Tested by 1

test_word_patternMethod · 0.72