def test_pop_one_item(self): value1 = 5 my_stack = Stack() my_stack.push(value1) popped_item = my_stack.pop() self.assertEqual(5, popped_item) self.assertEqual(0, my_stack.count)
def infix_to_postfix(infix_exp): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 op_stack = Stack() postfix_list = [] token_list = infix_exp.split() for token in token_list: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "1234567890": postfix_list.append(token) elif token == '(': op_stack.push(token) elif token == ')': top_token = op_stack.pop() while token != ')': postfix_list.append(top_token) top_token = op_stack.pop() else: while (not op_stack.is_empty()) and \ (prec[op_stack.peek()] >= prec[token]): postfix_list.append(op_stack.pop()) op_stack.push(token) while not op_stack.is_empty(): postfix_list.append(op_stack.pop()) return " ".join(postfix_list)
def eval(list): op = Stack() val = Stack() for i in list: if type(i)== int: val.push(int(val))
def test_peek_single_item(self): value1 = 5 my_stack = Stack() my_stack.push(value1) peeked_item = my_stack.peek() self.assertEqual(1, my_stack.count) self.assertEqual(5, peeked_item)
class QueueUsingStack: ''' Implementing Queue using two stacks We implement only enqueue and dequeue methods ''' def __init__(self): self.a_stack = Stack(20) self.b_stack = Stack(20) def enqueue(self, x): self.a_stack.push(x) print("Enqueueing element: {}\n".format(x)) print("A Stack: ", end="") self.a_stack.print() print("B Stack: ", end="") self.b_stack.print() print("---------------------------------------------") def dequeue(self): if not self.b_stack.isEmpty(): element = self.b_stack.pop() else: while (self.a_stack.top != 0): x = self.a_stack.pop() self.b_stack.push(x) element = self.a_stack.pop() print("Dequeued element: {}\n".format(element)) print("A Stack: ", end="") self.a_stack.print() print("B Stack: ", end="") self.b_stack.print() print("---------------------------------------------") return element
def test_check_not_empty(): s = Stack() s.push("apple") s.push("banana") actual = s.is_empty() expected = False assert actual == expected
def calc(expr): "Processes an expression written in Polish notation from left to right" # Create Stack objects for the operators and operands operatorStack = Stack() operandStack = Stack() # Split expression into a list (temporary) expr = expr.split() for token in expr: # Check if the token is an operator if token in ["+", "-", "*", "/"]: operatorStack.push(token) pendingOperand = False # Check if the operand is a valid number elif is_number(token): operand = token # Check if a calculation should be done if pendingOperand == True: while operandStack.height() != 0: operand_1 = operandStack.pop() operator = operatorStack.pop() # print("Evaluating " + str(operand_1) + " " + operator + " " + str(operand)) operand = evaluate(operator, operand_1, operand) # Push the number to the operand stack operandStack.push(operand) pendingOperand = True else: # Default if the token is not a operator or cannot be a float print(str(token) + " is not a valid token.") # Return result return operandStack.pop()
def test_peek(): s = Stack() s.push("apple") s.push("banana") actual = s.peek() expected = "banana" assert actual == expected
def rpn_calc(postfix_expr: str): '''Evaluate a postfix expression''' operand_stack = Stack() token_list = postfix_expr.split() print(postfix_expr) print(token_list) try: for ind in range(len(token_list)): if token_list[ind] in "0123456789": # Seperates the operands in a Stack operand_stack.push(int(token_list[ind])) else: # Does calculations with the operands operand2 = operand_stack.pop() operand1 = operand_stack.pop() result = do_math(token_list[ind], operand1, operand2) # If the Stack still has elements if ind == len(token_list) - 1 and not operand_stack.is_empty(): raise StackError( "Unknown expression {}".format(postfix_expr)) else: operand_stack.push(result) return (operand_stack.pop()) except IndexError: raise StackError("Stack is empty")
def check_tags(doc): s = Stack() tags = Stack() i = 0 stub = "" which = None balanced = True while balanced and i < len(doc): if doc[i] == "<": if s.is_empty(): s.push("<") if doc[i+1] == "/": which = "close" else: which = "open" else: balanced = False if not s.is_empty(): if doc[i] == ">": s.pop() if which == "open" tags.append(stub) stub = "" elif which == "close": last = tags.pop() if stub != last: balanced = False which = None stub = "" else: stub += doc[i] i += 1 if balanced and s.is_empty() and tags.is_empty(): return True return False
def toBase(decimal,base): # if base is greater than 16, raise error if base >16 or base <=0: raise ValueError ('base must be between 1 and 16') elif isinstance(decimal,int)==False: raise ValueError('the number must be a integer') elif decimal==0: return str(0) hex_num = "0123456789ABCDEF" s = Stack() while decimal > 0: remainder = decimal % base s.push(remainder) decimal = decimal // base output = "" # want to pop all the stack contents out while not s.isEmpty(): #hex_num[s.pop()] would make sure base>10, the alphabet would be used output += hex_num[s.pop()] return output #testing # print(toBase(101,2)) # should be 1100101 # print(toBase(101,16)) # should be 65 # print(toBase(188,16)) # should be BC
def make_stack(): stack = Stack() stack.push(23) stack.push(35) stack.push(56) stack.push(32) print(f"Stack: {stack.items}")
def reverse_queue(queue): stack = Stack() while not queue.is_empty(): stack.push(queue.dequeue()) while not stack.is_empty(): queue.enqueue(stack.pop())
def test_stack_push_two_items(self): value1, value2 = 5, 8 my_stack = Stack() my_stack.push(value1) self.assertEqual(1, my_stack.count) self.assertEqual(5, my_stack.ll.tail.value) my_stack.push(value2) self.assertEqual(2, my_stack.count) self.assertEqual(8, my_stack.ll.tail.value)
def test_peek_shows_top_of_2_item_stack(self): test_obj = Stack() test_data1 = 'data1' test_data2 = 'data2' test_obj.push(test_data1) test_obj.push(test_data2) self.assertEqual(test_data2, test_obj.peek()) self.assertEqual(False, test_obj.is_empty()) self.assertEqual(test_data2, test_obj.peek())
def test_sort_stack(): a = get_random_list(5) stack = Stack() for x in a: stack.push(x) stack.print_stack() sort_stack(stack) stack.print_stack()
def test_peek_multiple_items(self): value1, value2, value3 = 5, 8, 11 my_stack = Stack() my_stack.push(value1) my_stack.push(value2) my_stack.push(value3) peeked_item = my_stack.peek() self.assertEqual(3, my_stack.count) self.assertEqual(11, peeked_item)
def sortAscendingOrder(s1): s2 = Stack() while not s1.isEmpty(): # print 'S2:', s2.stack() # print 'S1:', s1.stack() last = s1.pop() while (not s2.isEmpty() and s2.peek() > last): s1.push(s2.pop()) s2.push(last) return s2
def find_closing_paren(string, start_paren): paren_stack = Stack() for i in range(start_paren, len(string)): ch = search_string[i] if ch == "(": paren_stack.push("(") elif ch == ")": paren_stack.pop() if paren_stack.is_empty(): return i
def test_pop_in_correct_order_from_2_item_stack(self): test_obj = Stack() test_data1 = 'data1' test_data2 = 'data2' test_obj.push(test_data1) test_obj.push(test_data2) self.assertEqual(test_data2, test_obj.pop()) self.assertEqual(False, test_obj.is_empty()) self.assertEqual(test_data1, test_obj.pop()) self.assertEqual(True, test_obj.is_empty())
def convert(num): s = Stack() while num > 0: remainder = num % 2 s.push(remainder) num = num // 2 bin_num = " " while not s.is_empty(): bin_num += str(s.pop()) return bin_num
def main(): p1 = Stack() p2 = Stack() p3 = Stack() num_disks = 6 for disk in range(num_disks): p1.push(num_disks - disk) arrange_hanoi(p1, p2, p3, num_disks) print(p1.length(), p2.length(), p3.length())
def reverseString (my_string): reverse_str="" x=Stack() """ we are using variable x as a stack variable as object of the previously defined stack class""" for s in my_string : x.push(s) for item in range(x.size()): reverse_str=reverse_str+x.pop() return reverse_str
def deciToBin(num): binaryStack = Stack() binNum = "" print(f"The binary of {num} is: ", end="") while num > 0: binaryStack.push(num % 2) num = num // 2 while not (binaryStack.isEmpty()): binNum += str(binaryStack.peek()) binaryStack.pop() print(binNum)
def reverse_str(string): s = Stack() for i in range(len(string)): s.push(string[i]) reverse_string = "" while not s.is_empty(): reverse_string += s.pop() return reverse_string
def searchDFS(graph, start): visited = [] stack = Stack() stack.push(start) while not stack.isEmpty(): vertex = stack.pop() if vertex not in visited: visited.append(vertex) print "VERTEX", vertex for edges in graph[vertex]: stack.push(edges) return visited
def reverse_string(string): """Return a string backwards.""" s = Stack() reverse_text = '' for char in string: s.push(char) s.container.reverse() for i in s.container: reverse_text += i print(reverse_text)
def stringReverse(s: str) -> str: #Creating a Stack Object stack = Stack() #For every character in string push to stack for x in s: stack.push(x) revStr = "" #The string to be returned #While the stack is not empty while not stack.isEmpty(): #Add the popped element to the revStr revStr += stack.pop() return revStr
def searchDFSTrace(graph, start, end): stack = Stack() stack.push([start]) while not stack.isEmpty(): path = stack.pop() last = path[-1] if last == end: return path for adjacent in graph.get(last, []): new_path = list(path) new_path.append(adjacent) stack.push(new_path)
def decimalToBinaryConverter(decimal_number): if not isinstance(decimal_number, int): raise Exception('Invalid object provided for conversion, valid datatype in INT') bin_stack = Stack() quotient = decimal_number remainder = None while quotient > 0: remainder = int(quotient % 2) quotient = int(quotient / 2) bin_stack.push(remainder) return str(bin_stack)
def searchDFS(graph, start): visited = [] stack = Stack() stack.push(start) while not stack.isEmpty(): vertex = stack.pop() if vertex not in visited: visited.append(vertex) print 'VERTEX', vertex for edges in graph[vertex]: stack.push(edges) return visited
def dfs_stack(self, v): """ Return a DFS tree from v, using a stack. """ marked = {v: None} stack = Stack() stack.push(v) while stack.length() > 0: vertex = stack.pop() for e in self.get_edges(vertex): w = e.opposite(vertex) if w not in marked: marked[w] = e stack.push(w) return marked
def test_pop_multiple_items(self): value1, value2, value3 = 5, 8, 11 my_stack = Stack() my_stack.push(value1) my_stack.push(value2) my_stack.push(value3) popped_item1 = my_stack.pop() popped_item2 = my_stack.pop() popped_item3 = my_stack.pop() self.assertEqual(0, my_stack.count) self.assertEqual(11, popped_item1) self.assertEqual(8, popped_item2) self.assertEqual(5, popped_item3)
def dfs_stack(self, v): """ Return a DFS tree from v, using a stack. """ marked = {v:None} stack = Stack() stack.push(v) while stack.length() > 0: vertex = stack.pop() for e in self.get_edges(vertex): w = e.opposite(vertex) if w not in marked: marked[w] = e stack.push(w) return marked
def depth_first_traversal(self, start): depth_list = [] new_stack = Stack([start]) while True: try: node = new_stack.pop() if node not in depth_list: depth_list.append(node) children = list(self.dict[node].keys()) for child in children: new_stack.push(child) except AttributeError: return depth_list
def matching_parens(text): open_parens = Stack() for c in text: try: if c == "(": open_parens.push(c) elif c == ")": open_parens.pop() except AttributeError: return -1 try: open_parens.pop() return 1 except AttributeError: return 0
class MaxStack: def __init__(self): self.stack = Stack() self.largest = Stack() def push(self, item): self.stack.push(item) if item >= self.largest.peek(): self.largest.push(item) def pop(self): item = self.stack.pop() if item == self.largest.peek(): self.largest.pop() return item def get_largest(self): return self.largest.peek()
def htmlChecker(html): stk = Stack() intag = False for index in xrange(len(html)): """Loops over html doc searching for tags when an opening bracket is found the tag is pushed onto the stack""" if html[index] == '<': intag = True count = index while intag: stk.push(html[count]) if html[count] == '>': intag = False else: count = count + 1 for index in xrange(len(html)): """Loops again over html doc but when tag is found it compares to popped item""" if html[index] == '<': intag = True count = index while intag: if len(stk) <= 0: return True else: item = stk.pop() if html[count] == '>': intag = False elif html[count] == '/' or item != '/': None elif html[count] != '/' and item != '/': if html[count] == '<' and item == '>'\ or html[count] == '>' and item == '<': count = count + 1 elif html[count] == item: count = count + 1 else: print count return False
def palindromeChecker(string): """Checks if 'string' is a palindrome""" holder = Stack() temp = Stack() isTrue = True for char in string: """Check for valid character before pushing to holder stack """ if 'a' <= char <= 'z' or 'A' <= char <= 'Z' or 0 <= char <= 9: holder.push(char) for i in xrange(len(holder)): """Pops from holder and compares value in 'string' """ if 'a' <= string[i] <= 'z' or 'A' <= string[i] <= 'Z' or '0' <= string[i] <= '9': temp.push(string[i]) item = holder.pop() if item != temp.pop(): isTrue = False return isTrue return isTrue
class minStack(Stack): def __init__(self): super(minStack,self).__init__() self.minSta = Stack() def pop(self): if self.minSta.peek() != None and self.minSta.peek() >= self.peek(): self.minSta.pop() return super(minStack, self).pop() def push(self, data): if self.minSta.peek() == None or self.minSta.peek() >= data: self.minSta.push(data) super(minStack, self).push(data) def peek(self): return super(minStack, self).peek() def min(self): return self.minSta.peek()
class Queue(): def __init__(self): self.base = Stack() self.buff = Stack() #insertion in O(n) def enqueue(self, data): while(True): try: self.buff.push(self.base.pop().data) except: self.base.push(data) while(True): try: self.base.push(self.buff.pop().data) except: break break #removal in O(1) def dequeue(self): return self.base.pop()
def get_path(v, tree): """ Extract a path from root to v, from backwards search tree. """ s = Stack() s.push(v) _get_path(v, tree, s) return s