def shuffle(self, cut=26, skill=1): left = Stack(self.deck[:cut:-1]) right = Stack(self.deck[cut::-1]) shuffled = [] if not isinstance(skill, int) or skill < 0 or skill > 1: raise CardError("Invalid input: check the skill parameters!") if not isinstance(cut, int) or cut < 0 or cut > 52: raise CardError("Invalid input: check the cut parameters!") if skill == 1: constant = True if skill != 1: percentage_error = 1 - skill possible_error = int(min(left, right) * percentage_error) possibilities = range(1, possible_error + 2) while left.stack and right.stack: if not constant: try: shuffled.append(right.pop(choice(possibilities))) except: shuffled.extend(right) try: shuffled.append(left.pop(choice(possibilities))) except: shuffled.extend(left) else: shuffled.append(right.pop()) shuffled.append(left.pop()) shuffled.extend(left) shuffled.extend(right) self.deck = shuffled return self.deck
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 buildParseTree(math_exp): mlist = math_exp.split() pStack = Stack() aTree = BinaryTree('') pStack.push(aTree) currentTree = aTree for num in mlist: # When we see open bracket, make a left child node since number will go there if num == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() # if it is operator, we set that parent to be the operator then make a right child elif num in ['+', '-', '*', '/']: currentTree.setRootVal(num) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() # closing the bracket so go back to the parent of the operator node elif num == ')': currentTree = pStack.pop() # this is presume to be a number, want to set the current node to that number, then go back to the parent elif num not in ['+', '-', '*', '/', ')']: try: currentTree.setRootVal(int(num)) parent = pStack.pop() currentTree = parent except ValueError: raise ValueError(num, "is not a valid integer") return aTree
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 build_parse_tree(p_exression): char_list = p_expression.split() s = Stack() current_node = BinaryTree('') s.push(current_node) for char in char_list: if char == '(': current_node.insert_left('') s.push(current_node) current_node = current_node.get_left_child() # for numeric values elif char not in "()+-*/%": current_node.set_root_val(int(char)) current_node = s.pop() # for operators elif char in "+-*/%": current_node.set_root_val(char) current_node.insert_right('') s.push(current_node) current_node = current_node.get_right_child() # if ')', then make the parent te current node (till there's no parent and the tree is thus complete) elif char == ')': current_node = s.pop() else: raise ValueError return current_node
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 build_parse(data): data = list(data) ops = Stack() tree = BinaryTree(" ") curr = tree print curr ops.push(tree) for i in data: if i == "(": curr.insert_left(" ") ops.push(curr) curr = curr.get_left() elif i not in '+-*/)': curr.set_root(int(i)) curr = ops.pop() elif i in '+-*/': curr.set_root(i) curr.insert_right(" ") ops.push(curr) curr = curr.get_right() elif i == ')': curr = ops.pop() else: raise ValueError("unsupported operator " + i) return tree
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 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 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 test_pop_some(): s = Stack() s.push("apple") s.push("banana") s.push("cucumber") s.pop() actual = s.pop() expected = "banana" assert actual == expected
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_until_empty(): s = Stack() s.push("apple") s.push("banana") s.push("cucumber") s.pop() s.pop() s.pop() actual = s.is_empty() expected = True assert actual == expected
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 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 postfixEval(postfixexpr): from stacks import Stack opStack = Stack() postfixList = ''.join( [' ' + x + ' ' if not x in digits else x for x in postfixexpr]) postfixList = postfixList.split() for x in postfixList: if not x in '*/+-': opStack.push(x) else: num1 = opStack.pop() num2 = opStack.pop() ## print(str(eval(num2 + x + num1))) opStack.push(str(eval(num2 + x + num1))) return opStack.pop()
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
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 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 sort_stack(stack): if stack.is_empty(): return stack temp = Stack() while not stack.is_empty(): if temp.is_empty(): temp.push(stack.pop()) else: val = stack.pop() while not temp.is_empty() and temp.peek() > val: stack.push(temp.pop()) temp.push(val) while not temp.is_empty(): stack.push(temp.pop())
class QueueFromStack: def __init__(self): self.in_storage = Stack() self.out_storage = Stack() def size(self): return self.in_storage.size() + self.out_storage.size() def enqueue(self, value): self.in_storage.push(value) def dequeue(self): if self.out_storage.size() == 0: while self.in_storage.size() != 0: self.out_storage.push(self.in_storage.pop()) return self.out_storage.pop()
def check_balanced_brackets(bracket_str): bracket_list = list(bracket_str) bracket_stack = Stack() for symbol in bracket_list: if symbol in ['(', '{', '[']: bracket_stack.push(symbol) continue elif symbol in [')', '}', ']']: if not bracket_stack.is_empty() and pair_match( symbol, bracket_stack.peak()): bracket_stack.pop() else: return False else: raise Exception('Invalid symbol found') return bracket_stack.is_empty()
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 par_checker(string): st=Stack() flag=True i=0 while i<len(string) and flag: ch=string[i] if(ch=="("): st.push(ch) else: if st.is_empty(): flag=False else: st.pop() i=i+1 if flag and st.is_empty(): return True else: return False
def generateMaze(nodes): nodes.getEmptyGrid() index = randint(0, len(nodes.nodeList)-1) nodeEnd = nodes.nodeList[index] nodeEnd.visited = True allNodesVisited = False #print "start = " + str(index) stack = Stack() while not allNodesVisited: unvisitedNodes = nodes.getUnvisitedNodes() index = randint(0, len(unvisitedNodes)-1) nodeStart = unvisitedNodes[index] endFound = False stack.push(nodeStart) while not endFound: directionList = nodes.getDirections(stack.peek()) directionIndex = randint(0, len(directionList)-1) direction = directionList[directionIndex] nodeNext = nodes.getUnlinkedNode(stack.peek(), direction) if not nodeNext.visited: if stack.contains(nodeNext): while stack.peek() is not nodeNext: stack.pop() else: stack.push(nodeNext) else: #Carve out the path that is defined by the stack stack.push(nodeNext) endFound = True while not stack.isEmpty(): node1 = stack.pop() node2 = stack.peek() node1.visited = True if node2 is not None: #print node1, node2 direction = nodes.getDirectionFromNodes(node1, node2) nodes.addPath(node1, direction) else: stack.clear() unvisitedNodes = nodes.getUnvisitedNodes() if len(unvisitedNodes) == 0: allNodesVisited = True
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 infixToPostfix(infixexpr): from stacks import Stack from string import digits, ascii_uppercase print(infixexpr) infixexpr = infixexpr.replace('**', '^') print(infixexpr) tokenList = ''.join( [' ' + x + ' ' if not x in digits else x for x in infixexpr]) tokenList = tokenList.split() print(tokenList) prec = {} prec['^'] = 4 prec['*'] = 3 prec['/'] = 3 prec['+'] = 2 prec['-'] = 2 prec['('] = 1 postfixList = [] opStack = Stack() for token in tokenList: if token in ascii_uppercase or token.isdigit(): postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': if not opStack.isEmpty(): topStack = opStack.pop() while not opStack.isEmpty() and topStack != '(': postfixList.append(topStack) topStack = opStack.pop() else: while not opStack.isEmpty() and prec[ opStack.peek()] >= prec[token]: postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) result = ' '.join(postfixList) result = result.replace('^', '**') return result
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 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 abs_to_relative_two(s): stack = Stack() index = 0 len_f = len(s) while index < len_f: while index< len_f and s[index] != '.': stack.push(s[index]) index += 1 point_count = 0 while index<len_f and s[index] == '.': index += 1 point_count += 1 if point_count == 2: stack.pop() while not stack.isEmpty() and stack.peer() != '/': stack.pop() index += 1 return ''.join(stack.items) # print relative path
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 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
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 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)
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()
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
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 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 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