diff --git a/src/my_project/interviews/top_150_questions_round_14/word_pattern.py b/src/my_project/interviews/top_150_questions_round_14/word_pattern.py new file mode 100644 index 00000000..e1b6fcb0 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_14/word_pattern.py @@ -0,0 +1,22 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod +from collections import defaultdict + +class Solution: + def wordPattern(self, pattern: str, s: str) -> bool: + + dic_answer = defaultdict(str) + words = s.split(' ') + + if len(words) != len(pattern) or len(set(pattern)) != len(set(words)): + return False + else: + for k, v in enumerate(words): + if v in dic_answer: + if dic_answer[v] != pattern[k]: + return False + else: + dic_answer[v] = pattern[k] + + return True + diff --git a/tests/test_150_questions_round_14/test_word_pattern_round_14.py b/tests/test_150_questions_round_14/test_word_pattern_round_14.py new file mode 100644 index 00000000..561b19db --- /dev/null +++ b/tests/test_150_questions_round_14/test_word_pattern_round_14.py @@ -0,0 +1,20 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_14\ +.word_pattern import Solution + +class WordPatternTestCase(unittest.TestCase): + + def test_is_word_pattern(self): + solution = Solution() + output = solution.wordPattern(pattern="abba", s="dog cat cat dog") + self.assertTrue(output) + + def test_is_no_word_pattern_one(self): + solution = Solution() + output = solution.wordPattern(pattern="abc", s="dog cat cat fish") + self.assertFalse(output) + + def test_is_no_word_pattern_two(self): + solution = Solution() + output = solution.wordPattern(pattern="aa", s="dog cat cat fish") + self.assertFalse(output)