class MyQueue: def __init__(self): self.s1 = Stack() self.s2 = Stack() self.end_first = True def add(self, data): if self.end_first: self.s1.push(data) else: self.transfer() self.add(data) def remove(self): if self.end_first: self.transfer() return self.remove() else: return self.s2.pop() def transfer(self): try: if self.end_first: while True: self.s2.push(self.s1.pop()) else: while True: self.s1.push(self.s2.pop()) except EmptyException: self.end_first = not self.end_first
class GUI(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.setFixedSize(self.size()) self.show() self.points = QtGui.QPolygon() self.undoStack = Stack() self.redoStack = Stack() create_shortcut(self, self.openShortcutEditor, 'Open Shortcut Editor', 'ctrl+f') create_shortcut(self, self.undo, 'Undo', 'ctrl+z') create_shortcut(self, self.redo, 'Redo', 'ctrl+y') self.defaultShortcuts = shortcutEditor.windowActionsToDict(self) shortcutEditor.loadSavedActions(self) def openShortcutEditor(self): self.editor = shortcutEditor(self, self.defaultShortcuts) self.editor.show() def undo(self): try: self.redoStack.push(self.undoStack.top()) self.points.remove(self.points.indexOf(self.undoStack.pop())) self.repaint() except EmptyStackException: pass def redo(self): try: self.undoStack.push(self.redoStack.top()) self.points.append(self.redoStack.pop()) self.repaint() except EmptyStackException: pass def mousePressEvent(self, e): if e.button() == 1: # left click self.points.append(e.pos()) self.undoStack.push(e.pos()) self.redoStack.clear() self.update() elif e.button() == 2: self.openShortcutEditor() def paintEvent(self, ev): qp = QtGui.QPainter(self) qp.setRenderHint(QtGui.QPainter.Antialiasing) pen = QtGui.QPen(QtCore.Qt.red, 5) brush = QtGui.QBrush(QtCore.Qt.red) qp.setPen(pen) qp.setBrush(brush) for i in range(self.points.count()): qp.drawEllipse(self.points.point(i), 5, 5)
def infix_to_postfix(infix_expression): """ Converts an infix expression to a postfix expression. Numerical operands must be integers. >>> infix_to_postfix('2 + 3') '2 3 +' >>> infix_to_postfix('2 + 3 * 4') '2 3 4 * +' >>> infix_to_postfix('(2 + 3) * 4') '2 3 + 4 *' >>> infix_to_postfix('2 + 3 * 2 - 5') '2 3 2 * + 5 -' >>> infix_to_postfix('(2 + 3) * (2 - 5)') '2 3 + 2 5 - *' >>> infix_to_postfix('(2 + 3) * (5 / 2)') '2 3 + 5 2 / *' """ # Split infix string into tokens. For example: # '2+3*4' => ['2', '+', '3', '*', '4'] tokens = re.findall(r'(\d+|\*|\+|\/|\-|\)|\(|\^)', infix_expression) output = [] stack = Stack() for s in tokens: if s not in OP_PREC: output.append(s) elif s == '(': stack.push(s) elif s == ')': item = stack.pop() while item != '(': output.append(item) item = stack.pop() else: while not stack.is_empty() and OP_PREC[s] <= OP_PREC[stack.peek()]: output.append(stack.peek()) stack.pop() stack.push(s) while not stack.is_empty(): output.append(stack.pop()) string = '' count = 0 for i in range(len(output) - 1): string += output[i] string += ' ' count += 1 string += output[-1] return string
def sort(stack): temp = Stack() count = None while True: maximum = stack.pop() i = 1 while not stack.empty(): if count is not None and i >= count: break node = stack.pop() if node > maximum: node, maximum = maximum, node temp.push(node) i += 1 count = 0 stack.push(maximum) while not temp.empty(): stack.push(temp.pop()) count += 1 if count == 0: break
def depth_first_search(self, board): moves = ['Up', 'Down', 'Left', 'Right'][::-1] frontier = Stack() explored = set() frontier.push(State(board)) nodes_expanded = 0 while not frontier.is_empty(): curr = frontier.pop() explored.add(curr) if curr.board == self.goalBoard: return curr, nodes_expanded nodes_expanded += 1 for move in moves: result = curr.board.move(move) if result is not None: result_state = State(result, move, curr, curr.depth + 1) if result_state not in explored and result_state not in frontier: State.max_depth = max(State.max_depth, result_state.depth) frontier.push(result_state)
def __build__(self,source): '''takes a properly formatted phrase file and builds the tree''' with open(source,'r') as f: lines = f.read().split('\n') wordStack = Stack(len(lines)//2) depth = 0 currWord = self.root last = None # Add create and children to WordNodes for i in range(len(lines)): #print(lines[i]) # Ignore comments if lines[i].strip().startswith('#'): continue if lines[i].find('#') != -1: lines[i] = lines[i].partition('#')[0].rstrip() tCount = lines[i].count('\t') # If tab depth increases if tCount > depth: wordStack.push(currWord) depth += 1 currWord = last # If tab depth decreases while tCount < depth: depth -= 1 currWord = wordStack.pop() # After the depth is adjusted, add the word to the tree last = WordNode(lines[i].strip()) currWord.children += [last] # Add codes to leaves self.__add_codes_rec__(self.root)
def __init__(self, data): """ Constructor """ if len(data) > 0: self.sorted_stack = Stack(deepcopy(data)) sorted = self.sorted_stack helper = Stack(['']) while sorted.node_data != '': top = sorted.pop() while helper.node_data != '' and helper.node_data < top: sorted.push(helper.pop()) helper.push(top) self.iterations += 1 while helper.node_data != '': sorted.push(helper.pop())
class SortStack: def __init__(self, args): from structures import Stack self.unsorted = Stack() for i in range(len(args)): self.unsorted.push(args[i]) self.sorted = Stack() def sort(self): while self.unsorted.top is not None: cur = self.unsorted.pop() self.move(cur) def move(self, cur): max = self.sorted.top if max is None or cur >= max.data: self.sorted.push(cur) else: self.unsorted.push(self.sorted.pop()) self.move(cur) self.sorted.push(self.unsorted.pop())
def evaluate_postfix(expression): """ Evaluates an expression in postfix notaion. Numerical operands must be integers. >>> evaluate_postfix('2 3 +') 5 >>> evaluate_postfix('2 3 4 * +') 14 >>> evaluate_postfix('2 3 + 4 *') 20 >>> evaluate_postfix('2 3 2 * + 5 -') 3 >>> evaluate_postfix('2 3 + 2 5 - *') -15 >>> evaluate_postfix('2 3 + 5 2 / *') 12.5 >>> evaluate_postfix('2 3 4 8 + * + 1 + 4 * 5 -') 151 """ # Split postfix string into tokens. For example: # '2 3 +' => ['2', '3', '+'] tokens = re.findall(r'(\d+|\*|\+|\/|\-|\)|\(|\^)', expression) list2 = [] stack = Stack() for symbol in tokens: if symbol not in OP_PREC: stack.push(symbol) else: list2.append(stack.pop()) list2.append(stack.pop()) alpha = float(list2[0]) beta = float(list2[1]) result = calculate(symbol, beta, alpha) list2.pop() list2.pop() stack.push(result) final = stack.pop() if final % int(final) == 0: final = round(final) return final
def dfs_walk(self): stack = Stack() stack.push(next(iter(self.nodes.values()))) while stack.size() > 0: first = stack.pop() if first.mark: continue else: print(first.name) first.mark = True for neighbour in first.connections: stack.push(self.nodes[neighbour])
def check_relation(label, x): # todo : need to add negation to each label. # label : a list of time_signature # x : a query for its label stack = Stack() unpop = [] modified = True for node in label: if node < x: if node.type == 'start': stack.push(node) # print('push') if node.type == 'end': if node.relation == stack.peek().relation: stack.pop() # print('pop') while (unpop and unpop[-1] == stack.peek().relation): stack.pop() # print('pop') unpop = unpop[:-1] else: unpop.append(node.relation) else: if not modified: if node.type == 'end' and stack.peek( ).relation[:3] == 'NOT' and node.relation[:3] != 'NOT': stack.push( time_signature('0000-00-00', relation=node.relation)) if stack.size() == 1: rel = node.relation else: rel = stack.peek().relation return rel else: rel = stack.peek().relation return rel
def evaluate_infix(infix_expression): """ Evaluates an infix expression. Numerical operands must be integers. >>> evaluate_infix('2 + 3 * 4') 14 >>> evaluate_infix('2 + (3 * 4)') 14 >>> evaluate_infix('(2 + 3) * 4') 20 >>> evaluate_infix('2 + 3 * 2 - 5') 3 >>> evaluate_infix('(2 + 3) * (2 - 5)') -15 >>> evaluate_infix('(2 + 3) * (5 / 2)') 12.5 """ # Split infix string into tokens. For example: # '2+3*4' => ['2', '+', '3', '*', '4'] tokens = re.findall(r'(\d+|\*|\+|\/|\-|\)|\(|\^)', infix_expression) operator = Stack() operand = Stack() for s in tokens: if s not in OP_PREC: #s is an integer operand.push(s) elif s == '(': operator.push(s) elif s == ')': item = operator.pop() while item != '(': alpha = float(operand.pop()) beta = float(operand.pop()) if item == '(': operator.pop() else: delta = calculate(item, beta, alpha) operand.push(delta) item = operator.pop() else: #s is an operator if len(operator) > 1 and len(operand) > 2: if OP_PREC[s] < OP_PREC[operator.peek()]: sign = operator.pop() alpha = float(operand.pop()) beta = float(operand.pop()) delta = calculate(sign, beta, alpha) operand.push(delta) operator.push(s) while not operand.is_empty() and not operator.is_empty(): sign = operator.pop() alpha = float(operand.pop()) beta = float(operand.pop()) delta = calculate(sign, beta, alpha) operand.push(delta) result = operand.pop() if result % int(result) == 0: result = round(result) return result
# print(lst) # print(lst.nodes) # stack = Stack() # stack.push(4) # stack.push(5) # stack.push(6) # print(stack.pop()) # stack.push(7) # print(stack) # print(stack.count) print('Stack:') stack = Stack([1, 2, 3]) print(stack) print(stack.peek()) stack.pop() print(stack) print(stack.peek()) print('Queue:') queue = Queue([1, 2, 3]) print(queue) print(queue.peek()) queue.dequeue() print(queue) print(queue.peek())
class Drawer: def __init__(self, getColor, screenshot, parent, offset): self.getColor = getColor self.parent = parent self.offset = offset self.resetDrawing(screenshot, offset) def resetDrawing(self, screenshot: QtGui.QPixmap, offset: QtCore.QPoint): """Called every time the user creates a new AOI.""" self.image = screenshot.toImage() self.offset = offset self.drawing = False # drawing right now self.ableToDraw = False # can drow (is the draw button pressed?) self.previousImages = Stack(self.image.copy()) self.nextImages = Stack() self.brushSize = 2 self.startingPoint = None self.lastPoint = QtCore.QPoint() def undo(self): try: self.nextImages.push(self.image.copy()) self.image = self.previousImages.pop() self.parent.repaint() except EmptyStackException: pass def redo(self): try: old = self.image.copy() self.image = self.nextImages.pop().copy() self.previousImages.push(old) self.parent.repaint() except EmptyStackException: pass def setDrawing(self, value: bool): self.drawing = value def setAbleToDraw(self, value: bool): self.ableToDraw = value def startDrawing(self, position): if self.ableToDraw: self.startingPoint = position self.previousImages.push(self.image.copy()) self.nextImages.clear() self.drawing = True self.lastPoint = position - self.offset def keepDrawing(self, position): if self.drawing and self.ableToDraw: painter = QPainter(self.image) painter.setPen( QtGui.QPen(self.getColor(), self.brushSize, QtCore.Qt.SolidLine, QtCore.Qt.RoundCap, QtCore.Qt.RoundJoin)) if self.startingPoint == position: painter.setBrush(self.getColor()) painter.drawEllipse(position - self.offset, self.brushSize, self.brushSize) else: painter.drawLine(self.lastPoint, position - self.offset) self.lastPoint = position - self.offset self.parent.update() def stopDrawing(self, position): if self.startingPoint == position: self.keepDrawing(position) # draw a circle self.drawing = False self.startingPoint = None def drawingNow(self): return self.drawing and self.ableToDraw
if len(case) % 2 != 0: return False if case[0] in closings: return False if case[-1] in openings: return False brackets = Stack() for elem in case: if elem in openings: brackets.push(elem) else: if elem != closings[brackets.pop()]: return False return len(brackets) == 0 class TestBalanceCheck(unittest.TestCase): def test_balance(self): self.assertEqual(balance_check('[]'), True) self.assertEqual(balance_check('[{](})'), False) self.assertEqual(balance_check('{()[]}'), True) self.assertEqual(balance_check('()()({)}'), False) if __name__ == '__main__': unittest.main()