Created
February 4, 2019 18:42
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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