Compare commits

...

5 Commits

Author SHA1 Message Date
pre-commit-ci[bot]
475b5b5184 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2023-08-14 05:32:57 +00:00
Amir Hosseini
8c5aef0497
Update dynamic_programming/regex_match.py
Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>
2023-08-14 09:02:30 +03:30
Amir Hosseini
4456366da0
Fix ruff formatting in if statements 2023-08-14 08:13:58 +03:30
Amir Hosseini
7271e3d2a5
Update dynamic_programming/regex_match.py
Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>
2023-08-14 08:07:37 +03:30
Amir Hosseini
c2bd6bf9a2
Update dynamic_programming/regex_match.py
Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>
2023-08-14 08:07:25 +03:30

View File

@ -30,17 +30,11 @@ def recursive_match(text: str, pattern: str) -> bool:
>>> recursive_match('aa', '.*') >>> recursive_match('aa', '.*')
True True
""" """
if not text and not pattern: if not pattern:
return True return not text
if text and not pattern: if not text:
return False return pattern[-1] == "*" and recursive_match(text, pattern[:-2])
if not text and pattern and pattern[-1] != "*":
return False
if not text and pattern and pattern[-1] == "*":
return recursive_match(text, pattern[:-2])
if text[-1] == pattern[-1] or pattern[-1] == ".": if text[-1] == pattern[-1] or pattern[-1] == ".":
return recursive_match(text[:-1], pattern[:-1]) return recursive_match(text[:-1], pattern[:-1])
@ -80,19 +74,16 @@ def dp_match(text: str, pattern: str) -> bool:
dp = [[False for _ in range(n + 1)] for _ in range(m + 1)] dp = [[False for _ in range(n + 1)] for _ in range(m + 1)]
dp[0][0] = True dp[0][0] = True
for i in range(1, m + 1):
dp[i][0] = False
for j in range(1, n + 1): for j in range(1, n + 1):
dp[0][j] = pattern[j - 1] == "*" and dp[0][j - 2] dp[0][j] = pattern[j - 1] == "*" and dp[0][j - 2]
for i in range(1, m + 1): for i in range(1, m + 1):
for j in range(1, n + 1): for j in range(1, n + 1):
if pattern[j - 1] == "." or pattern[j - 1] == text[i - 1]: if pattern[j - 1] in {".", text[i - 1]}:
dp[i][j] = dp[i - 1][j - 1] dp[i][j] = dp[i - 1][j - 1]
elif pattern[j - 1] == "*": elif pattern[j - 1] == "*":
dp[i][j] = dp[i][j - 2] dp[i][j] = dp[i][j - 2]
if pattern[j - 2] == "." or pattern[j - 2] == text[i - 1]: if pattern[j - 2] in {".", text[i - 1]}:
dp[i][j] |= dp[i - 1][j] dp[i][j] |= dp[i - 1][j]
else: else:
dp[i][j] = False dp[i][j] = False