From 6e408fae4e8c59f40b4f78b17753f7afa84e5a09 Mon Sep 17 00:00:00 2001 From: Dominic Date: Fri, 5 Oct 2018 11:55:14 -0500 Subject: [PATCH] implement balanced brackets in python --- Python/balanced-brackets.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Python/balanced-brackets.py diff --git a/Python/balanced-brackets.py b/Python/balanced-brackets.py new file mode 100644 index 000000000..74cc3ffe5 --- /dev/null +++ b/Python/balanced-brackets.py @@ -0,0 +1,21 @@ +PAIRINGS = { + '(': ')', + '{': '}', + '[': ']' +} + + +def is_balanced(symbols): + stack = [] + for s in symbols: + if s in PAIRINGS.keys(): + stack.append(s) + else: + try: + expected_opening_symbol = stack.pop() + except IndexError: # too many closing symbols + return False + if s != PAIRINGS[expected_opening_symbol]: # mismatch + return False + return len(stack) == 0 # false if too many opening symbols +