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 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 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 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 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
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 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 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)
def test_check_not_empty(): s = Stack() s.push("apple") s.push("banana") actual = s.is_empty() expected = False 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 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 test_peek(): s = Stack() s.push("apple") s.push("banana") actual = s.peek() expected = "banana" assert actual == expected
def test_push_onto_full(): s = Stack() s.push("apple") s.push("banana") s.push("cucumber") actual = s.top_of_list.value expected = "cucumber" assert actual == expected
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 make_stack(): stack = Stack() stack.push(23) stack.push(35) stack.push(56) stack.push(32) print(f"Stack: {stack.items}")
def __init__(self, width, height): self.nodeList = [] self.width = width self.height = height self.grid = None self.nodeStack = Stack() self.fRows = 0 self.fCols = 0
def __init__(self, level): self.level = level self.nodeList = [] self.grid = None self.nodeStack = Stack() self.nodeSymbols = ["+", "n", "N", "M", "H", "F"] self.homeList = [] self.createMainList() self.createHomeList()
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 parentheses_checker(string): opening_stack = Stack() closing_stack = Stack() opening_curly_braces = Stack() closing_curly_braces = Stack() for char in string: if re.match(r'\(', char): opening_stack.push(char) elif re.match(r'\)', char): closing_stack.push(char) elif re.match(r'\{', char): opening_curly_braces.push(char) elif re.match(r'\}', char): closing_curly_braces.push(char) if opening_stack.size() == closing_stack.size( ) and opening_curly_braces.size() == closing_curly_braces.size(): return True return False
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_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 __init__(self, width, height): '''width and height are the minimum distance between nodes''' self.nodeList = [] self.width = width self.height = height self.grid = None self.nodeStack = Stack() self.fRows = 0 self.fCols = 0
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 __init__(self, name, nr_containers): #print("port created") self.ship_queue = [] self.docks = [] self.ne_stacks = [] self.name = name self.nr_docks = 7 self.nr_non_empty_stacks = 16 self.max_capacity = 3000 for i in range(self.nr_docks): self.docks.append(Dock(i)) for i in range(8): self.ne_stacks.append(Stack(str(str(i)), "non empty", i, 0)) for i in range(8, 16): self.ne_stacks.append(Stack(str(str(i)), "non empty", i - 8, 1)) self.e_stack = Stack(str("E"), "empty", 0, 0) self.nr_containers = nr_containers self.date = 0 self.emptyC = 20
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 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 __init__(self, level): self.level = level self.nodeList = [] self.grid = None self.nodeStack = Stack() #self.createNodeList(MAZEDATA[level]["file"], self.nodeList) self.homeList = [] self.nodeSymbols = ["+", "n", "N", "M", "H", "F"] self.createMainList() self.createHomeList()
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