Skip to content

Instantly share code, notes, and snippets.

@temirlan42
Created September 26, 2019 12:16
Show Gist options
  • Save temirlan42/81cc46db522b8637a98e45fa82aa5b67 to your computer and use it in GitHub Desktop.
Save temirlan42/81cc46db522b8637a98e45fa82aa5b67 to your computer and use it in GitHub Desktop.
Stack
class Stack(object):
def __init__(self):
self._storage = {}
self._count = 0
def push(self, item):
self._storage[self._count] = item
self._count += 1
def pop(self):
item = self._storage[self._count - 1]
del self._storage[self._count - 1]
self._count -= 1
return item
def is_empty(self):
return True if self._count == 0 else False
def peek(self):
if (self.is_empty()):
raise 'The stack is empty'
return self._storage[self._count - 1]
def size(self):
return self._count
def pair_checker(symbols):
s = Stack()
open_brackets = ['{', '(', '[']
close_brackets = ['}', ')', ']']
for sym in symbols:
if sym in open_brackets:
s.push(sym)
elif sym in close_brackets:
close_bracket_ind = close_brackets.index(sym)
open_bracket_ind = None # the last opening bracket's index in the stack
try:
open_bracket_ind = open_brackets.index(s.peek())
except:
return False
if close_bracket_ind == open_bracket_ind:
s.pop()
else:
return False
return True if s.size() == 0 else False
print(pair_checker('{{([][])}()}')) # True
print(pair_checker('[{()]')) # False
print(pair_checker('{ { ( [ ] [ ] ) } ( ) }')) # True
print(pair_checker('[ ] [ ] [ ] ( ) { }')) # True
print(pair_checker('[ [ { { ( ( ) ) } } ] ]')) # True
print(pair_checker('( [ ) ]')) # False
print(pair_checker('( ( ( ) ] ) )')) # False
print(pair_checker('[ { ( ) ]')) # False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment