def match(text, pattern):
if not pattern: return not text
first_match = bool(text) and pattern[0] in {text[0], '.'}
return first_match and match(text[1:], pattern[1:])
I'm new to python and I don't understand the syntax. What is the purpose of elements in braces and what does "bool(text) and pattern[0] in {text[0], '.'}"
CodePudding user response:
In python, braces are used to create either a dictionary, or a set.
my_set = {1, 2, 3}
my_dict = {'a': 1, 'b': 2, 'c': 3}
bool(text) and pattern[0] in {text[0], '.'}
is checking whether the text is true (i.e. not empty or false), and the first element in pattern is either equal to text[0] or is a '.'
CodePudding user response:
If we were to destruct your function into distinct pieces, it will be easier to understand
def match(text: str, pattern: str) -> bool:
# if pattern is an empty string or None
if not pattern:
# True if text is empty string or None, otherwise - false
result: bool = not text
return result
# If text is empty or None return False
if not text:
return False
# Equivalent to set(first letter of text, dot)
# We use set/{} instead of list/[] or tuple/() to remove duplicates,
# however i don't see why should we care about duplicated dots here
subset: set = {text[0], '.'}
# If first letter of pattern is not in subset, return False
if pattern[0] not in subset:
return False
# Go one level deeper in recursion and return it's answer
result: bool = match(text[1:], pattern[1:])
return result
About curly braces. In python they mean two things:
- dict / dictionary:
{"foo": "bar", "count": 10}
- set / unique list:
{1, 2, 3, 3}
will create set{1, 2, 3}
Follow the links to learn more from python's docs