def checkPar(s): ''' check balanced parenthesis Args: s (str): string of parenthesis ''' S = Stack() for i in s: if S.isEmpty(): if i == '(': S.push(i) # imbalance else: return False else: if S.peek() == i: S.push(i) # cancel out parenthesis else: S.pop() # only if empty (all canceled out) then balanced return S.isEmpty()
def checkBalance(s, d={'(': ')', '[': ']', '{': '}', '<': '>'}): ''' check balanced symbols Args: s (str): string of parenthesis d (dict): dictionary key: open symbol, value = close symbol Returns: boolean: True if balanced, False if not balanced ''' S = Stack() for i in s: # push if open symbol if i in d: S.push(i) # unbalanced if no opening to match closing or mismatch open/close symbols elif S.isEmpty() or d[S.pop()] != i: return False # no need because popped in previous statment instead of peeked # there is a match in open/close so cancel out by popping # else: #S.pop() # only if empty (all canceled out) then balanced return S.isEmpty()
def checkBalance(s, d = {'(':')', '[':']', '{': '}', '<':'>'}): ''' check balanced symbols Args: s (str): string of parenthesis d (dict): dictionary key: open symbol, value = close symbol Returns: boolean: True if balanced, False if not balanced ''' S = Stack() for i in s: # push if open symbol if i in d: S.push(i) # unbalanced if no opening to match closing or mismatch open/close symbols elif S.isEmpty() or d[S.pop()] != i: return False # no need because popped in previous statment instead of peeked # there is a match in open/close so cancel out by popping # else: #S.pop() # only if empty (all canceled out) then balanced return S.isEmpty()
class Queue2Stack(object): def __init__(self): from datastructures import Stack self.inbox = Stack() self.outbox = Stack() def push(self,item): self.inbox.push(item) def pop(self): if self.outbox.isEmpty(): while not self.inbox.isEmpty(): self.outbox.push(self.inbox.pop()) return self.outbox.pop()
def infix2postfix(infixexpr): opstack = Stack() postfix_list = [] tokenlist = list(infixexpr.replace(' ', '')) for token in tokenlist: if token not in prec.keys() and token != ')': postfix_list.append(token) elif token == '(': opstack.push(token) elif token == ')': top_token = opstack.pop() while top_token != '(': postfix_list.append(top_token) top_token = opstack.pop() else: while (not opstack.isEmpty() and prec[opstack.peek()] >= prec[token]): postfix_list.append(opstack.pop()) opstack.push(token) while not opstack.isEmpty(): postfix_list.append(opstack.pop()) return ''.join(postfix_list)
def revstring(mystr): ''' Reverse the characters in a string using a stack Args: mystr (string): string to reverse Returns: string: reversed string ''' s = Stack() revmystr = "" for ch in mystr: s.push(ch) while not s.isEmpty(): revmystr += s.pop() return revmystr