Last active
August 29, 2015 14:03
-
-
Save ianmcnally/8ecf62ce3372e3c95be1 to your computer and use it in GitHub Desktop.
Balanced parenthesis
This file contains 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
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; | |
} |
This file contains 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
# 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