Reputation: 13
Here's the solution to leetcode problem: Regular expression matching.
I'm looking at this recursive approach but don't quite understand the logic of the first case. "if not pattern: return not text" what does that mean?
def isMatch(self, text, pattern):
if not pattern:
return not text
first_match = bool(text) and pattern[0] in {text[0], '.'}
if len(pattern) >= 2 and pattern[1] == '*':
return (self.isMatch(text, pattern[2:]) or
first_match and self.isMatch(text[1:], pattern))
else:
return first_match and self.isMatch(text[1:], pattern[1:])
I only want someone explain the first logic. Thanks.
Upvotes: 0
Views: 196
Reputation: 3758
when you put something into "if" statement, is should be evaluated to boolean.
if not pattern
means pattern should be evaluated to false for this "not pattern" to be "true". Then, return "not text", which again, evaluated to boolean
Some examples:
str = "bla"
>> not str
>> false
str = ""
>> not str
>> true
The pattern "if":
pattern = "some_pattern"
if not pattern:
print("no pattern") # nothing be printed
pattern = ""
if not pattern:
print("no pattern")
>> no pattern
Upvotes: 0
Reputation: 27283
not pattern
evaluates to True if the pattern is empty, False otherwise.
not text
evaluates to True if the text is empty, False otherwise.
if not pattern: return not text
therefore means: If the pattern is empty, return True if the text is empty, too. Otherwise return False.
A confusion matrix:
|Pattern \ Text | empty | non-empty |
|---------------------------------------|
|empty | True | False |
|---------------------------------------|
|non-empty | (rest of the code) |
|---------------------------------------|
Upvotes: 1