Created
September 13, 2019 12:56
-
-
Save firemanxbr/3ce9313518fc556ec38cf169eccad9fa to your computer and use it in GitHub Desktop.
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
Write a function that checks an expression has matching brackets and returns true if it does and false otherwise. | |
e.g. | |
'The is a (full) sentence.' -> True | |
'(x + y)/ 4' -> True | |
'(x + y / 4' -> False | |
'((2 + 3) * (5 + 7))' -> True | |
'((2 + 3) * (5 + 7)' -> False |
apahim
commented
Sep 13, 2019
from collections import Counter
def validate(sentence):
counter = Counter(sentence)
if counter.get('(') == counter.get(')'):
return True
return False
assert validate('The is a (full) sentence.')
assert validate('(x + y)/ 4')
assert not validate('(x + y / 4')
assert validate('((2 + 3) * (5 + 7))')
assert not validate('((2 + 3) * (5 + 7)')
assert not validate('()((((((')
assert validate('no brackets here')
from collections import Counter
from unittest import main
from unittest import TestCase
def validate(sentence):
counter = Counter(sentence)
if counter.get('(') == counter.get(')'):
return True
return False
class TestValidate(TestCase):
def test(self):
self.assertTrue(validate('The is a (full) sentence.'))
self.assertTrue(validate('(x + y)/ 4'))
self.assertFalse(validate('(x + y / 4'))
self.assertTrue(validate('((2 + 3) * (5 + 7))'))
self.assertFalse(validate('((2 + 3) * (5 + 7)'))
self.assertFalse(validate('()(((((('))
self.assertTrue(validate('no brackets here'))
if __name__ == '__main__':
main()
from collections import Counter
from unittest import main
from unittest import TestCase
def validate(sentence):
counter = Counter(sentence)
if counter.get('(') == counter.get(')'):
return True
return False
class TestValidate(TestCase):
def test_valid(self):
self.assertTrue(validate('The is a (full) sentence.'))
self.assertTrue(validate('(x + y)/ 4'))
self.assertTrue(validate('((2 + 3) * (5 + 7))'))
self.assertTrue(validate('no brackets here'))
def test_invalid(self):
self.assertFalse(validate('(x + y / 4'))
self.assertFalse(validate('((2 + 3) * (5 + 7)'))
self.assertFalse(validate('()(((((('))
if __name__ == '__main__':
main()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment