Skip to content

Instantly share code, notes, and snippets.

@kgaughan
Created February 4, 2019 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgaughan/b59ff82b11bcd92e7915945c694d02d6 to your computer and use it in GitHub Desktop.
Save kgaughan/b59ff82b11bcd92e7915945c694d02d6 to your computer and use it in GitHub Desktop.
Testing for Dyck words. Inspired by: http://raganwald.com/2018/11/14/dyck-joke.html
#!/usr/bin/env python3
def is_dyck_word(word):
i = 0
for ch in word:
if ch == '[':
i += 1
elif ch == ']':
i -= 1
# If at any point it goes below 0, there's an unbalanced ']'
if i < 0:
return False
# If there are unbalanced '[', i > 0.
return i == 0
def main():
positive_tests = [
"",
"[]"
"[][]",
"[[]]",
]
negative_tests = [
"][",
"[]]",
"[][][",
"][][",
]
for test in positive_tests:
assert is_dyck_word(test), f"Should be a dyck word: {test}"
for test in negative_tests:
assert not is_dyck_word(test), f"Should not be a dyck word: {test}"
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment