def reverse_list(self, l): st = ArrayStack() for k in range(len(l)): st.push(l[k]) for j in range(len(l)): l[j] = st.pop() return l
def AreaComputation(self, postfixExpression): stacky = ArrayStack() BestCandidate = 0 RealDict = {} RealNote = "" for y in range(0, 2**len(self._rectangles)): rectCounter = 0 flipDict = {} FlipNote = "{0:b}".format(y) FlipNote = "0"* (len(self._rectangles)-len(FlipNote)) + FlipNote for x in range(0, len(postfixExpression)): currentChar = postfixExpression[x] if (currentChar not in operator): rect = self._dictionnary[currentChar] flipDict[currentChar] = "0" if (FlipNote[rectCounter] == "1"): #print(rectCounter) #print(FlipNote) #print("Is flipping " + currentChar) flipDict[currentChar] = "1" rect = rect[::-1] stacky.push(rect) rectCounter += 1 else: Rightchild = stacky.pop() Leftchild = stacky.pop() rightWidth, rightHeight = Rightchild leftWidth, leftHeight = Leftchild if (currentChar == operator[0]): #Vertical slice stacky.push((rightWidth+leftWidth, (max(rightHeight,leftHeight)))) elif (currentChar == operator[1]): #Horizontal slice stacky.push((max(rightWidth,leftWidth),rightHeight+leftHeight)) else: print("Erreur AreaComputation. Invalid Operator in postfixExpression :" + postfixExpression + " " + postfixExpression[x]) #print(stacky) width, height = stacky.pop() area = width * height #print("Area : " + str(area)) if (area < BestCandidate or BestCandidate == 0): RealDict = flipDict BestCandidate = area RealNote = FlipNote RectRotation = "" #print("Best : " + str(BestCandidate)) ordered = OrderedDict(sorted(RealDict.items(), key=lambda t: t[0])) while(len(ordered) != 0): key, value = ordered.popitem(False) if(value == "1"): RectRotation += "0" elif (value =="0"): RectRotation += "1" #print(RectRotation) return RectRotation, BestCandidate
def reverse_file(self, filename): S = ArrayStack() original = open(filename) for line in original: S.push(line) original.close() out = open(filename, 'w') while not S.is_empty(): out.write(S.pop() + '\n') out.close()
def PostfixToPrefix(self, postfixExpression): stack = ArrayStack() stringPrefix = "" for x in range(0, len(postfixExpression)): if (postfixExpression[x] in operator): second = stack.pop() one = stack.pop() stack.push(postfixExpression[x]+one+second) else: stack.push(postfixExpression[x]) while (not stack.is_empty()): stringPrefix += stack.pop() return stringPrefix
def PrefixToPostfix(self, prefixExpression): stack = ArrayStack() stringPostfix = "" prefixExpression = prefixExpression[::-1] for x in range(0, len(prefixExpression)): if (prefixExpression[x] in operator): one = stack.pop() second = stack.pop() stack.push(one+second+prefixExpression[x]) else: stack.push(prefixExpression[x]) while (not stack.is_empty()): stringPostfix += stack.pop() return stringPostfix
def PostfixToInfix(self, postfixExpression): stack = ArrayStack() stringInfix = "" for x in range (0, len(postfixExpression)): if postfixExpression[x] not in operator: stack.push(postfixExpression[x]) else: op1 = stack.pop() op2 = stack.pop() stack.push(op1 + postfixExpression[x] + op2) while not stack.is_empty(): stringInfix += stack.pop() return stringInfix
def InfixToPostfix(self, infixExpression): stackyStack = ArrayStack() stringPostfix = "" for character in infixExpression: if (character not in operator): stringPostfix += character elif stackyStack.is_empty(): stackyStack.push(character) else: stringPostfix += stackyStack.pop() stackyStack.push(character) while (not stackyStack.is_empty()): stringPostfix += stackyStack.pop() return stringPostfix
def ChildParentOperatorTest(self, postfixExpression): stack = ArrayStack() for x in range(0, len(postfixExpression)): if postfixExpression[x] not in operator: stack.push(postfixExpression[x]) else: op2 = stack.pop() op1 = stack.pop() if op1[-1] == postfixExpression[x] or op2[-1] == postfixExpression[x]: return False stack.push(op1 + op2 + postfixExpression[x]) return True
def parentheses_match(expr): """ Return True if all delimiters are properly match; False otherwise.""" left = '({[' # opening delimiters right = ')}]' # respective closing delims S = ArrayStack() for c in expr: if c in left: S.push(c) # push left delimiter on stack elif c in right: if S.is_empty(): # nothing to match with return False if right.index(c) != left.index(S.pop()): return False # mismatched return S.is_empty() # were all symbols matched?
def is_matched(self, expr): """ Running time : O(n) :return: true if there are matching opening/closing symbols """ lefty = '({[' righty = ')}]' S = ArrayStack() for c in expr: if c in lefty: S.push(c) elif c in righty: if S.is_empty(): return False if righty.index(c) != lefty.index(S.pop()): return False return S.is_empty()
def is_matched_html(self, raw): """ :return: True if there are correct opening and closing html tags """ s = ArrayStack() j = raw.find('<') while j != -1: k = raw.find('>', j+1) if k == -1: return False tag = raw[j+1:k] # strip < > if not tag.startswith('/'): # opening tag s.push(tag) else: if s.is_empty(): return False if tag[1:] != s.pop(): return False j = raw.find('<', k+1) return s.is_empty()
def __init__(self): self._s = ArrayStack() self._t = ArrayStack()
def test_three_stack(): R = ArrayStack() R.push(1) R.push(2) R.push(3) S = ArrayStack() S.push(4) S.push(5) T = ArrayStack() T.push(6) T.push(7) T.push(8) T.push(9) three_stack(R, S, T) # check result print("Stack R") for _ in range(len(R)): print(R.pop()) print("Stack S") for _ in range(len(S)): print(S.pop())
def eval_expr(expression): operand_stack = ArrayStack() operator_stack = ArrayStack() for i in range(len(expression)): if expression[i] == '(': continue elif expression[i] in '0123456789': operand_stack.push(int(expression[i])) elif expression[i] in '+-*/': operator_stack.push(expression[i]) elif expression[i] == ')': op2 = operand_stack.pop() op1 = operand_stack.pop() op = operator_stack.pop() operand_stack.push(compute(op1,op2,op)) return operand_stack.pop()
__author__ = 'maskari' from ArrayStack import ArrayStack class StackTransfer: def transfer(self, s, t): while not s.is_empty(): t.push(s.pop()) if __name__ == '__main__': st = StackTransfer() s1 = ArrayStack() s2 = ArrayStack() s1.push(1) s1.push(2) s1.push(3) # s1 = [1, 2, 3] print(s1) st.transfer(s1, s2) # s2 = [3, 2, 1] print(s2)
def __init__(self): self._stack = ArrayStack() self._inverted = False self._size = 0
def __init__(self): self.data = ArrayStack() self.curr_max = None
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys sys.path.append( "/Users/liangy/data-structure-algorithms-python/Stacks-queues-Deques") from ArrayStack import ArrayStack, Empty def transfer(S, T): while not S.is_empty(): T.push(S.pop()) if __name__ == "__main__": S = ArrayStack() S.push(1) S.push(2) T = ArrayStack() transfer(S, T) print(T.pop()) print(T.pop())
""" Show how to use the transfer function, described in Exercise R-6.3, and two temporary stacks, to replace the contents of a given stack S with those same elements, but in reversed order. """ from ArrayStack import ArrayStack def transfer(S, T): while not S.is_empty(): T.push(S.pop()) data = ArrayStack() [data.push(x) for x in list(range(10))] s1 = ArrayStack() s2 = ArrayStack() transfer(data, s1) transfer(s1, s2) transfer(s2, data) print(data.look())
def __init__(self): self.top_deque = ArrayDeque() self.bottom_stack = ArrayStack()
def main(): aStack = ArrayStack() lList = LinkedList() lStack = LinkedStack() print(type(node))
"""Using the ArrayStack object to reverse data""" from ArrayStack import ArrayStack data = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] stack = ArrayStack() before = '' after = '' for num in data: before += str(num) + ',' stack.push(num) while not stack.is_empty(): after += str(stack.pop()) + ',' print(before) print(after)
def __init__(self): self.data = ArrayStack()
def __init__(self): self.data = ArrayStack() self.reorder = ArrayDeque()
class Queue: def __init__(self): self.stack = ArrayStack() self.helper = ArrayStack() def __len__(self): return len(self.stack) def is_empty(self): return len(self) == 0 def enqueue(self,elem): self.stack.push(elem) def first(self): if self.is_empty(): raise Exception("The Queue is empty") for i in range(len(self)): self.helper.push(self.stack.pop()) val = self.helper.top() for i in range(len(self)): self.stack.push(self.helper.pop()) return val def dequeue(self): if self.is_empty(): raise Exception("The Queue is empty") for i in range(len(self)): self.helper.push(self.stack.pop()) val = self.helper.pop() for i in range(len(self.helper)): self.stack.push(self.helper.pop()) return val
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys sys.path.append( "/Users/liangy/data-structure-algorithms-python/Stacks-queues-Deques") from ArrayStack import ArrayStack, Empty def recursive_remove(S): if S.is_empty(): return S.pop() return recursive_remove(S) if __name__ == "__main__": S = ArrayStack() S.push(1) S.push(2) recursive_remove(S, 2) print(len(S))
def main(): S = ArrayStack() print(len(S)) S.push(5) S.push(3) print(len(S)) print(S.pop()) print(S.is_empty()) print(S.pop()) print(S.is_empty()) S.push(7) S.push(9) print(S.top()) S.push(4) print(len(S)) print(S.pop()) S.push(6)
def __init__(self): self.enq = ArrayStack() self.deq = ArrayStack()
def postfix(): operators = "+-*/" stack = ArrayStack() while x != 'done()': x = input("-->") if "=" in x: equalPosition = x.find('=') variable_name = '' for k in range(0, equalPosition - 1): variable_name += x[k] for j in range(equalPosition + 2, len(x)): if x[j] not in operators: stack.push(int(x[j])) else: operand_1 = stack.pop() operand_2 = stack.pop() if (j == '+'): res = operand_2 + operand_1 elif (j == '-'): res = operand_2 - operand_1 elif (j == '*'): res = operand_2 * operand_1 else: res = operand_2 / operand_1 stack.push(res) else: for i in x: if i not in operators: stack.push(int(i)) else: operand_1 = stack.pop() operand_2 = stack.pop() if (i == '+'): res = operand_2 + operand_1 elif (i == '-'): res = operand_2 - operand_1 elif (i == '*'): res = operand_2 * operand_1 else: res = operand_2 / operand_1 stack.push(res) print(stack.pop())
def __iadd__(self, other): selfStack = ArrayStack() otherStack = ArrayStack() result = Integer("") for elem in self.number: selfStack.push(elem) for i in range(len(self.number) - len(other.number)): otherStack.push(0) for elem in other.number: otherStack.push(elem) hold = 0 for i in range(len(otherStack)): resultDigit = str((selfStack.pop() + otherStack.pop() + hold)) if (len(resultDigit) == 2): hold = int(resultDigit[0]) result.number.add_first(int(resultDigit[1])) else: hold = 0 result.number.add_first(int(resultDigit)) result.number.add_first(hold) while (result.number.header.next.data == 0 and len(result.number) > 1): result.number.delete_first() return result
def postfix_calc(): exp = input('-->') dct = {} s = ArrayStack() while exp != 'done()': exp = input('-->') if '=' not in exp: for char in exp: if char.isdigit() == True: s.push(char) elif char in '*-/+': operand1 = int(s.pop()) operand2 = int(s.pop()) if char == '+': s.push(operand1 + operand2) elif char == '-': s.push(operand1 + operand2) elif char == '*': s.push(operand1 * operand2) elif char == '/': s.push(operand1 * operand2) print(s.top()) else: for char in exp: if char.isalpha() == True: dct[char] = stack.top() print(char)
"""Using the ArrayStack object to reverse a string""" from ArrayStack import ArrayStack forward = "Never odd or even" reverse = "" stack = ArrayStack() for char in forward: stack.push(char) while not stack.is_empty(): reverse += str(stack.pop()) print(forward) print(reverse)
class MaxStack: def __init__(self): self.data = ArrayStack() def __len__(self): return len(self.data) def is_empty(self): return len(self.data) == 0 def top(self): if (self.data.is_empty()): raise Exception("Stack is empty") return self.data.top()[0] def push(self, val): if self.data.is_empty(): self.data.push((val, val)) elif self.data.top()[1] > val: self.data.push((val, self.data.top()[1])) else: self.data.push((val, val)) def pop(self): if self.data.is_empty(): raise Exception("Stack is empty") return self.data.pop()[0] def max(self): if self.data.is_empty(): raise Exception("Stack is empty") return self.data.top()[1]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys sys.path.append( "/Users/liangy/data-structure-algorithms-python/Stacks-queues-Deques") from ArrayStack import ArrayStack, Empty from r603 import transfer def reverse_stack(S): s1 = ArrayStack() s2 = ArrayStack() transfer(S, s1) transfer(s1, s2) transfer(s2, S) if __name__ == "__main__": S = ArrayStack() S.push(3) S.push(2) S.push(1) reverse_stack(S) for _ in range(3): print(S.pop())
__author__ = 'Stephen' # Given a string of an arithmetic expression, design an algorithm, using a stack, to evaluate it from ArrayStack import ArrayStack import operator ops = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div} arithmetic = "3 + 3" parts = arithmetic.split() stack = ArrayStack(len(parts)) stack.push(int(parts[0])) stack.push(parts[1]) stack.push(int(parts[2])) number1 = stack.pop() op = stack.pop() number2 = stack.pop() stack.push(ops[op](number1, number2)) print stack
def reverse_stack(S): s1 = ArrayStack() s2 = ArrayStack() transfer(S, s1) transfer(s1, s2) transfer(s2, S)
def postixcalculator(expression, mydict): operators, temp = "-/+*", "" user_input = expression.split(" ") stack = ArrayStack() for elem in user_input: if elem in operators: right = stack.pop() left = stack.pop() if elem == "+": stack.push(left + right) elif elem == "-": stack.push(left - right) elif elem == "*": stack.push(left * right) else: # elem == "/" if right == 0: raise Exception("Divide by Zero Error") stack.push(left / right) elif elem in mydict: stack.push(mydict[elem]) elif elem.isdigit(): stack.push(int(elem)) elif elem.isalpha(): stack.push(elem) temp += elem if temp == "": val = stack.top() print(val) else: mydict[temp] = stack.top() print(temp) return (stack.top())
class StackQueue(): """Implement ADT queue using two stacks""" def __init__(self): self._s = ArrayStack() self._t = ArrayStack() def __len__(self): return len(self._s) + len(self._t) def is_empty(self): return self._s.is_empty() and self._t.is_empty() def enqueue(self, value): self._s.push(value) def dequeue(self): if not self._t.is_empty(): return self._t.pop() else: if self._s.is_empty(): raise ValueError("Empty Queue") else: while not self._s.is_empty(): self._t.push(self._s.pop()) return self._t.pop()
def __init__(self): self._stack = ArrayStack()
class Queue: def __init__(self): self.enq = ArrayStack() self.deq = ArrayStack() def __len__(self): return len(self.deq) def is_empty(self): return len(self.deq) == 0 def first(self): if self.deq.is_empty(): raise Exception("Queue is Empty") else: return self.deq.top() def enqueue(self, val): if self.deq.is_empty(): self.deq.push(val) else: for q in range(len(self.deq)): self.enq.push(self.deq.pop()) self.enq.push(val) for q in range(len(self.enq)): self.deq.push(self.enq.pop()) def dequeue(self): if self.deq.is_empty(): raise Exception("Queue is Empty") else: return self.deq.pop()