MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / is_match

Function is_match

dynamic_programming/wildcard_matching.py:19–61  ·  view source on GitHub ↗

>>> is_match("", "") True >>> is_match("aa", "a") False >>> is_match("abc", "abc") True >>> is_match("abc", "*c") True >>> is_match("abc", "a*") True >>> is_match("abc", "*a*") True >>> is_match("abc", "?b?") True >>> is_match("abc", "*?")

(string: str, pattern: str)

Source from the content-addressed store, hash-verified

17
18
19def is_match(string: str, pattern: str) -> bool:
20 """
21 >>> is_match("", "")
22 True
23 >>> is_match("aa", "a")
24 False
25 >>> is_match("abc", "abc")
26 True
27 >>> is_match("abc", "*c")
28 True
29 >>> is_match("abc", "a*")
30 True
31 >>> is_match("abc", "*a*")
32 True
33 >>> is_match("abc", "?b?")
34 True
35 >>> is_match("abc", "*?")
36 True
37 >>> is_match("abc", "a*d")
38 False
39 >>> is_match("abc", "a*c?")
40 False
41 >>> is_match('baaabab','*****ba*****ba')
42 False
43 >>> is_match('baaabab','*****ba*****ab')
44 True
45 >>> is_match('aa','*')
46 True
47 """
48 dp = [[False] * (len(pattern) + 1) for _ in string + "1"]
49 dp[0][0] = True
50 # Fill in the first row
51 for j, char in enumerate(pattern, 1):
52 if char == "*":
53 dp[0][j] = dp[0][j - 1]
54 # Fill in the rest of the DP table
55 for i, s_char in enumerate(string, 1):
56 for j, p_char in enumerate(pattern, 1):
57 if p_char in (s_char, "?"):
58 dp[i][j] = dp[i - 1][j - 1]
59 elif pattern[j - 1] == "*":
60 dp[i][j] = dp[i - 1][j] or dp[i][j - 1]
61 return dp[len(string)][len(pattern)]
62
63
64if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected