def infixtopostfix(string): comp = string.split(' ') output = [] operator_precedence = {"+": 1, "-": 1, "/": 2, "*": 2, "(": 3, ")": 3} operator_stack = Stack() for value in comp: if value in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or value in '0123456789': output.append(value) elif value == '(': operator_stack.push(value) elif value == ')': operator = operator_stack.pop() while operator != '(': output.append(operator) operator = operator_stack.pop() else: while not operator_stack.isEmpty() and \ operator_precedence[operator_stack.peek()] <= operator_precedence[value]: output.append(operator_stack.pop()) operator_stack.push(value) while not operator_stack.isEmpty(): token = operator_stack.pop() output.append(token) return ' '.join(output)
def parenthesis_checker(symbolString): """ Read a string of parenthesis from left to right and decide whether the symbols are balanced """ S = Stack() #Input are valid if symbolString is None: raise TypeError("cannot be none") if not symbolString: raise ValueError("cannot be empty") for char in symbolString: if char == "(": S.push(char) elif char == "[": S.push(char) elif char == "{": S.push(char) else: if S.isEmpty(): return False else: S.pop() return S.isEmpty()
def parChecker(symbolString): ''' in: a string containing all symbols return: boolean, true for balaced, vice versa Completed extended parenthesis checker for: [,{,(,),},] ''' leftPar = Stack() strList = list(symbolString) balanced = True symbol = {'[':']','{':'}','(':')'} i = 0 while i < len(symbolString) and balanced: if strList[i] in ['[','(','{']: leftPar.push(strList[i]) else: if leftPar.isEmpty(): balanced = False else: if not strList[i] == symbol[leftPar.pop()]: balanced = False i += 1 if not leftPar.isEmpty(): balanced = False return balanced
def infixToPostfix(infixexpr): precedence = {} precedence["*"] = 3 precedence["/"] = 3 precedence["+"] = 2 precedence["-"] = 2 precedence["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = opStack.pop() else: while (not opStack.isEmpty()) and \ (precedence[opStack.peek()] >= precedence[token]): postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) return " ".join(postfixList)
def balanced_parentheses(paren_str): """problem involving applications of stack""" # filter out all values besides brackets matches = re.finditer(r'[(){}[\]]+', paren_str) parsed_iter = itertools.chain.from_iterable( result.group() for result in matches) opening = Stack() for i in parsed_iter: if i in ("(", "{", "["): opening.add(i) else: if not opening.isEmpty(): if i == ")" and opening.peek() == "(": opening.get() elif i == "}" and opening.peek() == "{": opening.get() elif i == "]" and opening.peek() == "[": opening.get() else: return False else: return False return True
def paranthesis_checker(string): stack = Stack() balanced = True index = 0 while index < len(string) and balanced: symbol = string[index] if symbol == '(': stack.push(symbol) else: if stack.isEmpty(): balanced = False else: stack.pop() index = index + 1 if balanced and stack.isEmpty(): return True else: return False
def parChecker(string): s = Stack() i = 0 balanced = True while i < len(string) and balanced: symbol = string[i] if symbol in "([{": s.push(symbol) elif s.isEmpty(): balanced = False elif symbol in ")]}": top = s.pop() if not matches(top, symbol): balanced = False i += 1 if balanced and s.isEmpty(): return True else: return False
def HexToBinary(number): bin_holder = Stack() while number > 0: rem = number % 2 bin_holder.push(rem) number = number // 2 bin_string = "" while not bin_holder.isEmpty(): bin_string = bin_string + str(bin_holder.pop()) return bin_string
def revstringstack(str): # with stack implemented stack = Stack() for char in str: stack.add(char) new_str = '' while not stack.isEmpty(): new_str += stack.get() return new_str
class TestStack(unittest.TestCase): @staticmethod def add_to_structure(self, items): for i in items: self.structure.add(i) def setUp(self): self.structure = Stack() def test_structure_isEmpty(self): self.assertEqual(self.structure.isEmpty(), True) self.add_to_structure(self, range(3)) self.assertEqual(self.structure.isEmpty(), False) def test_structure_peek(self): structure = self.add_to_structure( self, iter(['people', 'potatoes', 'pansies'])) self.assertEqual(self.structure.peek(), 'pansies') def test_structure_get_length(self): structure = self.add_to_structure(self, range(5)) self.assertEqual(self.structure.get_length(), 5) def test_structure_get(self): structure = self.add_to_structure(self, range(3)) # test that first in are first out for i in reversed(range(3)): self.assertEqual(self.structure.get(), i) def test_empty_items(self): # for when get, or peek is called on empty structure self.assertRaises(EmptyItemsError, lambda: self.structure.get()) self.assertRaises(EmptyItemsError, lambda: self.structure.peek())
def baseConverter(decNum, base): digits = "0123456789ABCDEF" remstack = Stack() while decNum > 0: remainder = decNum % base remstack.push(remainder) decNum = decNum // base newString = "" while not remstack.isEmpty(): newString = newString + digits[remstack.pop()] return newString
def revstring(mystr): """ :type mystr: string :rtype: string use Stack Last In First Out feature to reverse a string """ aStack = Stack() for i in list(mystr): aStack.push(i) revstr = "" while not aStack.isEmpty(): revstr += aStack.pop() return revstr
def baseConverter(decNumber,base): ''' decNumber: decimal number base: int between 2 and 16 Algorithm for binary conversion can easily be extended to perform the conversion for any base. In computer science it is common to use a number of different encodings. The most common of these are binary, octal (base 8) , and hexadecimal (base 16). ''' baseNumber = '' reminders = Stack() while decNumber > 0: reminders.push(decNumber%base) decNumber = decNumber//base while not reminders.isEmpty(): baseNumber += str(reminders.pop()) return baseNumber
def single_dfs(big_list, current): stack = Stack() explored = Queue() pointer = current stack.push(pointer) explored.enqueue(pointer) tra_model = Tra_model() while True: if stack.isEmpty(): break else: pointer = stack.peek() x = pointer[0] y = pointer[1] if big_list[x][y + 1] == " ": #if right is empty pointer = tra_model.move_right(pointer) stack.push(pointer) explored.enqueue(pointer) x = pointer[0] y = pointer[1] big_list[x][y] = "#" continue #return to the top of the loop if big_list[x][y + 1] == ".": pointer = tra_model.move_right(pointer) stack.push(pointer) explored.enqueue(pointer) break if big_list[x][y + 1] == "%" or "#": #if right is wall if big_list[x + 1][y] == " ": #if down is empty pointer = tra_model.move_down(pointer) stack.push(pointer) explored.enqueue(pointer) x = pointer[0] y = pointer[1] big_list[x][y] = "#" continue if big_list[x + 1][y] == ".": pointer = tra_model.move_down(pointer) stack.push(pointer) explored.enqueue(pointer) break if big_list[x + 1][y] == "%" or "#": # if down is wall if big_list[x - 1][y] == " ": # if up is empty pointer = tra_model.move_up(pointer) stack.push(pointer) explored.enqueue(pointer) x = pointer[0] y = pointer[1] big_list[x][y] = "#" continue # return to the top of the loop if big_list[x - 1][y] == ".": pointer = tra_model.move_up(pointer) stack.push(pointer) explored.enqueue(pointer) break if big_list[x - 1][y] == "%" or "#": #if up is wall if big_list[x][y - 1] == " ": #if left is empty pointer = tra_model.move_left(pointer) stack.push(pointer) explored.enqueue(pointer) x = pointer[0] y = pointer[1] big_list[x][y] = "#" continue #return to the top if big_list[x - 1][y] == ".": pointer = tra_model.move_left(pointer) stack.push(pointer) explored.enqueue(pointer) break if big_list[x][y - 1] == "%" or "#": big_list[x][y] = "*" stack.pop() expanded = 0 for i in explored.items: expanded += 1 x = i[0] y = i[1] if big_list[x][y] == "*": big_list[x][y] = " " steps = 0 for i in explored.items: x = i[0] y = i[1] if big_list[x][y] == "#": steps += 1 return explored, big_list, steps, expanded