From d1bb71b25f397af966ef9567c20ea8db53ed282b Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 24 Dec 2024 04:32:50 -0600 Subject: [PATCH] adding word pattern --- .../word_pattern.py | 20 +++++++++++++++++ .../test_word_pattern_round_12.py | 22 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_12/word_pattern.py create mode 100644 tests/test_150_questions_round_12/test_word_pattern_round_12.py diff --git a/src/my_project/interviews/top_150_questions_round_12/word_pattern.py b/src/my_project/interviews/top_150_questions_round_12/word_pattern.py new file mode 100644 index 00000000..f9d7c16b --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_12/word_pattern.py @@ -0,0 +1,20 @@ +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(pattern): + if v in dic_answer: + if dic_answer[v] != words[k]: + return False + else: + dic_answer[v] = words[k] + return True \ No newline at end of file diff --git a/tests/test_150_questions_round_12/test_word_pattern_round_12.py b/tests/test_150_questions_round_12/test_word_pattern_round_12.py new file mode 100644 index 00000000..d539ca6b --- /dev/null +++ b/tests/test_150_questions_round_12/test_word_pattern_round_12.py @@ -0,0 +1,22 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_12\ +.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) + + \ No newline at end of file