From 023303faff7fcb0e97bf810341bb8cbe57b369f2 Mon Sep 17 00:00:00 2001 From: ivan Date: Mon, 18 Nov 2024 04:04:30 -0600 Subject: [PATCH] adding word pattern algo --- .../word_pattern.py | 21 +++++++++++++++++++ .../top_word_pattern_round_11.py | 20 ++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_11/word_pattern.py create mode 100644 tests/test_150_questions_round_11/top_word_pattern_round_11.py diff --git a/src/my_project/interviews/top_150_questions_round_11/word_pattern.py b/src/my_project/interviews/top_150_questions_round_11/word_pattern.py new file mode 100644 index 00000000..12d0ea65 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_11/word_pattern.py @@ -0,0 +1,21 @@ +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(words)) != len(set(pattern)): + 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 diff --git a/tests/test_150_questions_round_11/top_word_pattern_round_11.py b/tests/test_150_questions_round_11/top_word_pattern_round_11.py new file mode 100644 index 00000000..8e414494 --- /dev/null +++ b/tests/test_150_questions_round_11/top_word_pattern_round_11.py @@ -0,0 +1,20 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_11\ +.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