Skip to content

Instantly share code, notes, and snippets.

@johnny-morrice
Created May 25, 2020 14:38
Show Gist options
  • Save johnny-morrice/b4fab59d857fb43aa36046b98f3c0be4 to your computer and use it in GitHub Desktop.
Save johnny-morrice/b4fab59d857fb43aa36046b98f3c0be4 to your computer and use it in GitHub Desktop.
from unittest import TestCase, main
def valid_parentheses(string):
x = 0
for char in string:
if char == '(':
x += 1
elif char == ')':
if x == 0:
return False
x -= 1
return x == 0
class TestValidParenthesis(TestCase):
def test_open_only_is_invalid(self):
self.assertNotValid("(")
def test_close_only_is_invalid(self):
self.assertNotValid(")")
def test_valid_section_first_then_open_is_invalid(self):
self.assertNotValid("((()))(")
def test_valid_section_first_then_close_is_invalid(self):
self.assertNotValid("((())))")
def test_one_matching_paren_is_valid(self):
self.assertIsValid("()")
def test_three_matching_paren_is_invalid(self):
self.assertIsValid("((()))")
def test_many_paren_sections_is_valid(self):
self.assertIsValid("((()))()((((()))))(())")
def assertNotValid(self, parens):
self.assertFalse(valid_parentheses(parens))
def assertIsValid(self, parens):
self.assertTrue(valid_parentheses(parens))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment