Skip to content

Instantly share code, notes, and snippets.

@ianmcnally
Last active August 29, 2015 14:03
Show Gist options
  • Save ianmcnally/8ecf62ce3372e3c95be1 to your computer and use it in GitHub Desktop.
Save ianmcnally/8ecf62ce3372e3c95be1 to your computer and use it in GitHub Desktop.
Balanced parenthesis
function isBalanced(string) {
var closers = {
'{' : '}',
'(' : ')',
'[' : ']'
}
var stack = [];
for (var i = 0, l = string.length; i < l; i++) {
if (closers[string[i]]) {
stack.push(string[i]);
} else {
if (closers[stack.pop()] !== string[i]) {
return false;
}
}
}
return stack.length === 0;
}
# Check a string for balanced parenthesis
def is_balanced(string):
if len(string) % 2:
return False
closers = {
'(' : ')',
'{' : '}',
'[' : ']'
}
opened = []
for ch in string:
is_opener = closers.get(ch)
if is_opener:
opened.append(ch)
else:
if closers.get(opened.pop()) != ch:
return False
return True
if __name__ == '__main__':
import unittest
class TestIsBalanced(unittest.TestCase):
def test_balanced(self):
self.assertTrue(is_balanced('()'))
self.assertTrue(is_balanced('{()}[]'))
self.assertTrue(is_balanced('[({})]'))
self.assertTrue(is_balanced('(())'))
def test_unbalanced(self):
self.assertFalse(is_balanced('('))
self.assertFalse(is_balanced('[(])'))
self.assertFalse(is_balanced('[{]}'))
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment