Skip to content

Instantly share code, notes, and snippets.

@yoniLavi
Last active August 2, 2023 15:53
Show Gist options
  • Select an option

  • Save yoniLavi/ed76302aaf982df7de14f13b8082fc9d to your computer and use it in GitHub Desktop.

Select an option

Save yoniLavi/ed76302aaf982df7de14f13b8082fc9d to your computer and use it in GitHub Desktop.
An alternative single function implementation for the challenge in https://third-bit.com/sdxpy/glob/
def match(text: str, pattern: str) -> bool:
"""Determine whether the text matches the glob pattern.
>>> match('', '')
True
>>> match('abc', 'abc')
True
>>> match('abcd', 'abc')
False
>>> match('aabc', 'abc')
False
>>> match('abc', 'a*bc')
True
>>> match('abc', 'a*c')
True
>>> match('abcc', 'a*c')
True
>>> match('abc', 'ac*c')
False
>>> match('whatever', '*')
True
>>> match('abc', 'a{b,d}c')
True
>>> match('abc', 'a{a,d}c')
False
>>> match('abc', 'a{b,d}cc')
False
"""
if not pattern:
return not text
if pattern[0] == '*':
return any(match(text[start:], pattern[1:]) for start in range(len(text)+1))
elif pattern[0] == '{':
closing = pattern.index('}')
alternatives = pattern[1:closing].split(',')
return any(text.startswith(a) and match(text[len(a):], pattern[closing+1:]) for a in alternatives)
return text.startswith(pattern[0]) and match(text[1:], pattern[1:])
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment