def queue_to_stack(my_queue): q = deepcopy(my_queue) s = LinkedStack() while not q.isEmpty(): s.add(q.peek()) q.pop() return s
def test_linkedstack_pop_returnselement(self): stack = LinkedStack() for i in range(10): stack.push(i + 1) for i in range(10): val = stack.pop() assert_equal(10 - i, val) assert_equal(10 - i - 1, len(stack))
def _is_palindrom(word): ls = LinkedStack() for i in range(len(word) // 2): ls.add(word[i]) md = len(word) // 2 if len(word) % 2 == 0 else len(word) // 2 + 1 for i in range(md, len(word)): if ls.pop() != word[i]: return False return True
def test_push_to_stack(self): name = "Jose" node = Node(name) stack = LinkedStack() stack.push(node) self.assertEqual(len(stack), 1)
def _is_palindrom(word): ls = LinkedStack() for i, c in enumerate(word): if i < len(word) // 2: ls.push(c) elif i >= (len(word) - 1) // 2 + 1: if c != ls.pop(): return False return True
def node_preorder(self): if not self.isEmpty(): stack = LinkedStack() stack.push(self._root) while not stack.isEmpty(): node = stack.pop() yield node if node.right != None: stack.push(node.right) if node.left != None: stack.push(node.left)
def queue_to_stack(queue): """Return a stack that contains items from the queue.""" stack = LinkedStack() item_list = [] for item in queue: item_list.insert(0, item) for item in item_list: stack.push(item) return stack
def preorder(self): """Supports a preorder traversal on a view of self.""" if not self.isEmpty(): treeStack = LinkedStack() treeStack.push(self._root) while not treeStack.isEmpty(): node = treeStack.pop() yield node.data if node.right != None: treeStack.push(node.right) if node.left != None: treeStack.push(node.left)
def __iter__(self): """Supports a preorder traversal on a view of self.""" if not self.isEmpty(): stack = LinkedStack() stack.push(self._root) while not stack.isEmpty(): node = stack.pop() yield node.data if node.right is not None: stack.push(node.right) if node.left is not None: stack.push(node.left)
def test_pop_from_stack(self): name = "Jose" node = Node(name) stack = LinkedStack() stack.push(node) self.assertEqual(len(stack), 1) popped = stack.pop() self.assertEqual(popped, node) self.assertEqual(len(stack), 0)
def topo_sort(g, start_label=None): stack = LinkedStack() g.clear_vertex_marks() for v in g.vertices(): if not v.is_marked(): dfs(g, v, stack) return stack
def levelorder(self): """Supports a levelorder traversal on a view of self.""" if not self.isEmpty(): stack = LinkedStack() stack.push(self.root) yield self.root.data while not stack.isEmpty(): node = stack.pop() if node.left != None: yield node.left.data stack.push(node.right) if node.right != None: yield node.right.data stack.push(node.left)
def topoSort(g, startLabel=None): stack = LinkedStack() g.clearVertexMarks() for v in g.vertices(): if not v.isMarked(): dfs(g, v, stack) return stack
def topoSort(chart): stack = LinkedStack() chart.clearVertexMarks() for v in chart.vertices(): if not v.isMarked(): dfs(chart, v, stack) return stack
def isPalindrome(word: str) -> bool: ''' True if a word read from left equal to from right else False. ''' wordLen = len(word) if wordLen == 1 or wordLen == 0: return True stack = LinkedStack() middle = wordLen // 2 for index in range(0, middle): stack.push(word[index]) for index in range(wordLen - middle, wordLen): if word[index] != stack.pop(): return False return True
def height(self): hgt = LinkedStack() def recurse(node, count): if node != None: if count > hgt.peek(): hgt.push(hgt.pop() + 1) recurse(node.left, count + 1) recurse(node.right, count + 1) if self.isEmpty(): return None else: hgt.push(-1) recurse(self.root, 0) return hgt.pop()
def operate(self): '''Operate the postfix expression.''' stack = LinkedStack() for operand in self._tokens: if operand not in PostfixExpression._operator: # push the operand to the stack stack.push(operand) else: # operate two operand on the top of stack with the operation opRight = float(stack.pop()) opLeft = float(stack.pop()) res = PostfixExpression._operator[operand](opLeft, opRight) # push the result onto the stack stack.push(res) return stack.pop()
def traverseFromVertex(graph, startVertex, process, collection=LinkedStack()): chart.clearVertexMarks() collection.add(startVertex) while not collection.isEmpty(): v = collection.pop() if not v.isMarked(): v.setMark() process(v) for vertex in v.neighboringVertices(): if not vertex.isMarked(): collection.add(vertex)
def successor(self, item): #FIXME: Incomplete succ = LinkedStack() def recurse(node, item): if node != None: if item >= node.data: recurse(node.right, item) elif item < node.data: succ.push(node.data) recurse(node.left, item) if self.isEmpty(): return None else: recurse(self.root, item) result = None if not succ.isEmpty(): result = succ.pop() return result
def predecessor(self, item): pred = LinkedStack() def recurse(node, item): if node != None: if item <= node.data: recurse(node.left, item) elif item > node.data: pred.push(node.data) recurse(node.right, item) if self.isEmpty(): return None else: recurse(self.root, item) result = None if not pred.isEmpty(): result = pred.pop() return result
def is_palindrome(word): stack = LinkedStack() for index in range(len(word) // 2): stack.push(word[index]) for index in range((len(word) + 1) // 2, len(word)): if stack.peek() == word[index]: stack.pop() else: return False return True
def predecessor(self, item): """ Returns the largest item that is smaller than item, or None if there is no such item. :param item: :type item: :return: :rtype: """ biggest = 0 if not self.isEmpty(): stack = LinkedStack() stack.push(self._root) while not stack.isEmpty(): node = stack.pop() if biggest <= node.data <= item: biggest = node.data if node.right != None: stack.push(node.right) if node.left != None: stack.push(node.left) return biggest if biggest != 0 else None
def brackets_Checker(): stk = LinkedStack() for ch in exp: if ch in ['[', '(']: stk.push(ch) elif ch in [']', ')']: if stk.isEmpty(): return False chFromStack = stk.pop() if ch == ']' and chFromStack != '[' or ch == ')' and chFromStack != '(': return False return stk.isEmpty()
def rangeFind(self, low, high): ''' Returns a list of the items in the tree, where low <= item <= high.""" :param low: :param high: :return: ''' lst = [] if not self.isEmpty(): stack = LinkedStack() stack.push(self._root) while not stack.isEmpty(): node = stack.pop() if low <= node.data <= high: lst.append(node.data) if node.right != None: stack.push(node.right) if node.left != None: stack.push(node.left) return lst
def bracketsBalance(exp): """exp is a string that represents the expression """ stk = LinkedStack() for ch in exp: if ch in ['[', '(']: stk.push(ch) elif ch in [']', ')']: if stk.isEmpty(): return False chFromStack = stk.pop() # Brackets must be of same type and match up if ch == ']' and chFromStack != '[' or ch == ')' and chFromStack != '(': return False return stk.isEmpty()
def bracketsBalance(exp): """exp is s string that represents the expression""" stk = LinkedStack() for ch in exp: if ch in ["[", "("]: stk.push(ch) elif ch in [']', ')']: if stk.isEmpty(): return False chFromStck = stk.pop() if ch == ']' and chFromStck != '[' or \ ch == ')' and chFromStck != '(' : return False return stk.isEmpty()
def bracketsBalance(exp): """exp represents the expression""" stk = LinkedStack() # Create a new stack for ch in exp: # Scan across the expression if ch in ['[', '(']: # Push an opening bracket stk.push(ch) elif ch in [']', ')']: # Process a closing bracket if stk.isEmpty(): # Not balanced return False chFromStack = stk.pop() # Brackets must be of same type and match up if ch == ']' and chFromStack != '[' or \ ch == ')' and chFromStack != '(': return False return stk.isEmpty() # They all matched up
def bracketsBalance(exp): #checks if the parentheses and brackets all match stk = LinkedStack() for l in exp: if l in ['(','[']: stk.push(l) #push opening braces onto the stack elif l in [')',']']: if stk.isEmpty(): return False #the list began with a closing bracket fromStack = stk.pop() if (l == '(' and fromStack != ')') or (l == '[' and fromStack != ']'): return False #non-matching symbols if stk.isEmpty(): return True #they all matched up
class Evaluator(object): """Evaluator for postfix expressions. Assumes that the input is a syntactically correct sequence of tokens.""" def __init__(self, scanner): """Sets the initial state of the evaluator.""" self._operandStack = LinkedStack() self._scanner = scanner def evaluate(self): """Returns the value of the postfix expression.""" for currentToken in self._scanner: if currentToken.getType() == Token.INT: self._operandStack.push(currentToken) elif currentToken.isOperator(): right = self._operandStack.pop() left = self._operandStack.pop() result = Token(self._computeValue(currentToken, left.getValue(), right.getValue())) self._operandStack.push(result) result = self._operandStack.pop() return result.getValue(); def _computeValue(self, op, value1, value2): """Utility routine to compute a value.""" result = 0 theType = op.getType() if theType == Token.PLUS: result = value1 + value2 elif theType == Token.MINUS: result = value1 - value2 elif theType == Token.MUL: result = value1 * value2 elif theType == Token.REMDR: result = value1 % value2 elif theType == Token.EXPO: result = value1 ** value2 elif theType == Token.DIV: if value2 == 0: raise ZeroDivisionError("Attempt to divide by 0") else: result = value1 // value2 return result
def is_palindrome(word: str) -> bool: """Check whether the word is a palindrome.""" stack = LinkedStack() for index, char in enumerate(word, 1): if char.isalpha() and index <= len(word) / 2: stack.push(char) elif char.isalpha() and (index > len(word) / 2) \ and (index != (len(word) / 2) + 0.5): if stack.isEmpty(): return False char_from_stack = stack.pop() if char != char_from_stack: return False return stack.isEmpty()
def is_palindrome(self, word): # check if word is palindrome half_1, half_2 = word[:len(word) // 2], word[len(word) // 2:] # cut first letter, whcih is not important if len(half_2) != len(half_1): half_2 = half_2[1:] stack = LinkedStack() for let in half_1: stack.push(let) for i in range(len(half_2)): if half_2[i] != stack.peek(): return 0 stack.pop() return 1
class Evaluator(object): """Evaluator for postfix expressions. Assumes that the input is a syntactically correct sequence of tokens.""" def __init__(self, scanner): """Sets the initial state of the evaluator.""" self._operandStack = LinkedStack() self._scanner = scanner def evaluate(self): """Returns the value of the postfix expression.""" for currentToken in self._scanner: if currentToken.getType() == Token.INT: self._operandStack.push(currentToken) elif currentToken.isOperator(): right = self._operandStack.pop() left = self._operandStack.pop() result = Token( self._computeValue(currentToken, left.getValue(), right.getValue())) self._operandStack.push(result) result = self._operandStack.pop() return result.getValue() def _computeValue(self, op, value1, value2): """Utility routine to compute a value.""" result = 0 theType = op.getType() if theType == Token.PLUS: result = value1 + value2 elif theType == Token.MINUS: result = value1 - value2 elif theType == Token.MUL: result = value1 * value2 elif theType == Token.REMDR: result = value1 % value2 elif theType == Token.EXPO: result = value1**value2 elif theType == Token.DIV: if value2 == 0: raise ZeroDivisionError("Attempt to divide by 0") else: result = value1 // value2 return result
"""
class Translator(object): """Translates infix expressions to postfix expressions.""" def __init__(self, scanner): """Sets the initial state of the translator.""" self._expressionSoFar = "" self._operatorStack = LinkedStack() self._scanner = scanner def translate(self): """Returns a list of tokens that represent the postfix form of sourceStr. Assumes that the infix expression in sourceStr is syntactically correct""" postfix = list() for currentToken in self._scanner: self._expressionSoFar += str(currentToken) + " " if currentToken.getType() == Token.INT: postfix.append(currentToken) elif currentToken.getType() == Token.LPAR: self._operatorStack.push(currentToken) elif currentToken.getType() == Token.RPAR: topOperator = self._operatorStack.pop() while topOperator.getType() != Token.LPAR: postfix.append(topOperator) topOperator = self._operatorStack.pop() else: while not self._operatorStack.isEmpty() and \ self._operatorStack.peek().getPrecedence() >= \ currentToken.getPrecedence(): postfix.append(self._operatorStack.pop()) self._operatorStack.push(currentToken) while not self._operatorStack.isEmpty(): postfix.append(self._operatorStack.pop()) return postfix def __str__(self): """Returns a string containing the contents of the expression processed and the stack to this point.""" result = "\n" if self._expressionSoFar == "": result += "Portion of expression processed: none\n" else: result += "Portion of expression processed: " + \ self._expressionSoFar + "\n" if self._operatorStack.isEmpty(): result += "The stack is empty" else: result += "Operators on the stack : " + \ str(self._operatorStack) return result def translationStatus(self): return str(self)
def __init__(self, scanner): """Sets the initial state of the translator.""" self._expressionSoFar = "" self._operatorStack = LinkedStack() self._scanner = scanner
def __init__(self, scanner): """Sets the initial state of the evaluator.""" self._operandStack = LinkedStack() self._scanner = scanner