def convert(self): # cache the result if not self._pfTokens: # save the converted expression (tokens) self._pfTokens = [] # stack to store operators and operands stack = LinkedStack() for token in self._scanner: # append the operand to list if not token.isOperator(): self._pfTokens.append(token) # Token.OPENPAREN & Token.CLOSEPAREN are operators, # so must be called before token.isOperator(). elif token.getType() == Token.OPENPAREN: stack.push(token) elif token.getType() == Token.CLOSEPAREN: for i in range(len(stack)): operator = stack.pop() if operator.getType() == Token.OPENPAREN: break self._pfTokens.append(operator) elif token.isOperator(): # pop operators in the stack whose precedence is not smaller for i in range(len(stack)): if (stack.peek().getType() == Token.OPENPAREN or stack.peek().getPrecedence() < token.getPrecedence()): break self._pfTokens.append(stack.pop()) stack.push(token) for i in range(len(stack)): self._pfTokens.append(stack.pop()) return self._pfTokens
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 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 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
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 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 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 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
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 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 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 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 mazeSolver(maze, start, to_text=False, data_structure='stack'): """takes a maze and its starting point (as a tuple of row, column) and solves the maze. Maze walls must be * characters and the ending point must be a "T" character. Free spaces must be an empty space, " ". """ # read the grid and set up stack grid = maze_reader(maze) print("maze without attempts:\n", grid) if data_structure == 'stack': _queue = LinkedStack() else: _queue = LinkedQueue( ) #TODO implement a linkedQueue structure with push _queue.push(start) # track choices: choice_count = 0 #use stack data structure to explore maze and find a path to the end. while not _queue.isEmpty(): _pop = _queue.pop() # print("popping ",_pop) if grid[_pop[0]][_pop[1]] == 'T': choice_count += 1 print("Finished maze: \n") print(grid) if to_text: maze_text(grid, "solution.txt") return choice_count else: # if the _pop location did not return the character "T", leave a breadcrumb to not revisit. if grid[_pop[0]][_pop[1]] != 'O' and grid[_pop[0]][ _pop[1]] != 'T' and grid[_pop[0]][_pop[1]] != 'P': choice_count += 1 grid[_pop[0]][_pop[1]] = 'O' # print("grid row, column is ",_pop[0],_pop[1],"\n") # print(grid) left = grid[_pop[0]][(_pop[1] - 1)] right = grid[_pop[0]][(_pop[1] + 1)] down = grid[(_pop[0] - 1)][_pop[1]] up = grid[(_pop[0] + 1)][_pop[1]] if left == ' ' or left == 'T': _queue.push((_pop[0], (_pop[1] - 1))) if right == ' ' or right == 'T': _queue.push((_pop[0], (_pop[1] + 1))) if up == ' ' or up == 'T': _queue.push(((_pop[0] + 1), _pop[1])) if down == ' ' or down == 'T': _queue.push(((_pop[0] - 1), _pop[1])) #if stack becomes empty, there is no path. return choice_count
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()
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 Polindrom(LinkedStack): """docstring for Polindrom.""" def __init__(self): self.dictionary = LinkedStack() self.polindroms = [] def read_dict(self, filename): """reads data from file and saves it to dictionary""" with open(filename, encoding='utf-8', errors='ignore') as f: lines = f.readlines() if ".lst" in filename: for line in lines: self.dictionary.push(line.split()[0]) # counter = 0 # with open("try.txt", "w") as t: # while counter < 30: # t.write(lines[counter].split()[0]+"\n") # counter += 1 # self.dictionary.push(line.strip()) else: for line in lines: self.dictionary.push(line.strip()) def process_dict(self): """looks for polindroms in processed dict and returns a list of them""" while not self.dictionary.isEmpty(): isPolindrom = True curr_word = self.dictionary.pop() curr_word_len = len(curr_word) if curr_word_len > 1: for i in range(curr_word_len // 2): if curr_word[i].lower() == curr_word[ curr_word_len - i - 1].lower() and isPolindrom: isPolindrom = True else: isPolindrom = False if isPolindrom: self.polindroms.append(curr_word) def write_dict(self, filename): """writes data from polindroms to file""" with open(filename, "w", encoding='utf-8', errors='ignore') as f: for item in self.polindroms: f.write(item) f.write("\n")
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
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()
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 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 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 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 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 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
"""
lst_cases = [] for line in f: lst = [] stk = LinkedStack() line = line.strip() case = line for j in range(len(case)): if case[j] == '+': lst.append(1) else: lst.append(-1) lst.reverse() for item in lst: stk.push(item) lst_cases.append(stk) def main(case): num_man = 0 if case.sum() == -len(case): return 1 while True: if case.sum() == len(case): return num_man item = case.pop() lst_popped = [-item] next_item = case.peek() while item == next_item:
def lipeek_unit_test(self): temp = LinkedStack() for count in range(5): temp.push(count+1) self.assertEqual(temp.peek(), 5)
def lipush_unit_test(self): temp = LinkedStack() for count in range(20): temp.push(count+1) self.assertEqual(len(temp),20)
def liclear_unit_test(self): temp = LinkedStack() for count in range(4): temp.push(count+1) temp.clear() self.assertEqual(temp.isEmpty(), True)