def hanoi_problem(num, left, mid, right): """ 处理汉诺塔问题 :param num: 汉诺塔最大层数 :param left: :param mid: :param right: :return: """ ls = Stack() ms = Stack() rs = Stack() ls.push(sys.maxsize) ms.push(sys.maxsize) rs.push(sys.maxsize) for i in reversed(range(1, num + 1)): ls.push(i) record = [Action.No] step = 0 while rs.size() != num + 1: step += fStackTotStack(record, Action.MToL, Action.LToM, ls, ms, left, mid) step += fStackTotStack(record, Action.LToM, Action.MToL, ms, ls, mid, left) step += fStackTotStack(record, Action.RToM, Action.MToR, ms, rs, mid, right) step += fStackTotStack(record, Action.MToR, Action.RToM, rs, ms, right, mid) # print(ls) # print(ms) # print(rs) return step
def infix_to_prefix(expr): prec = { ')': 0, '+': 1, '-': 1, '*': 2, '/': 2 } output = deque() s = Stack() # Process starting from the last item for c in expr[::-1]: if c == ')': s.push(c) elif c == '(': while not s.is_empty() and s.top() != ')': output.appendleft(s.pop()) s.pop() elif c in prec: # notice it is not >= here, as we handling from right to left # so if it is equal, the one comes at left should handled first while not s.is_empty() and prec[s.top()] > prec[c]: output.appendleft(s.pop()) s.push(c) else: output.appendleft(c) while not s.is_empty(): output.appendleft(s.pop()) return "".join(output)
def infix_to_postfix(expr): prec = { '(': 0, '+': 1, '-': 1, '*': 2, '/': 2 } output = [] s = Stack() # handle differently for 4 cases for c in expr: if c == '(': s.push(c) elif c == ')': while not s.is_empty() and s.top() != '(': output.append(s.pop()) s.pop() elif c in prec: while not s.is_empty() and prec[s.top()] >= prec[c]: output.append(s.pop()) s.push(c) else: output.append(c) while not s.is_empty(): output.append(s.pop()) return "".join(output)
def test_push(): stack = Stack() stack.push(1) assert stack.back() == 1 assert stack.size == 1 stack.push(3) assert stack.back() == 3
def sort_stack2(stack): if stack.is_empty(): return stack new_stack = Stack() while not stack.is_empty(): cur = stack.pop() while (not new_stack.is_empty()) and (new_stack.peek() > cur): stack.push(new_stack.pop()) new_stack.push(cur) return new_stack
def sort(stack): new_stack = Stack() length = stack.length print(length) for _ in range(length): min_value = get_min(stack) # print(min_value) new_stack.push(min_value) remove(stack, min_value) print(new_stack)
def eval_prefix(expr): s = Stack() for c in expr[::-1]: # from right to left if c in oper: a = int(s.pop()) # notice the order of a, b b = int(s.pop()) s.push(oper[c](a, b)) else: s.push(c) return s.pop()
def eval_postfix(expr): s = Stack() for c in expr: if c in oper: b = int(s.pop()) a = int(s.pop()) s.push(oper[c](a, b)) else: s.push(c) return s.pop()
def is_brace_balanced(expr): assert isinstance(expr, str), 'argument must be of str type' stack = Stack() for char in expr: if char in "{[(": stack.push(char) elif char in "}])": if (not stack.is_empty()) and is_pair(stack.top(), char): stack.pop() else: return False return stack.is_empty()
def test_pop(): stack = Stack() stack.push(1) assert stack.size == 1 assert stack.pop() == 1 assert stack.size == 0 stack.push(3) stack.push(1) assert stack.pop() == 1 assert stack.size == 1 assert stack.pop() == 3 assert stack.size == 0
def decimal_to_binary_stack(decimal): s = Stack() while decimal > 1: mod = decimal % 2 s.push(mod) div = decimal / 2 decimal = div s.push(decimal) # convert stack to a string result = [] while not s.is_empty(): result.append(str(s.pop())) return "".join(result)
def get_max_tree(data_list): l_big_map = {} r_big_map = {} stack = Stack() node_list = [] for data in data_list: node_list.append(Node(data)) for cur_node in node_list: while (not stack.is_empty() ) and stack.peek().get_value() < cur_node.get_value(): pop_stack_set_map(stack, l_big_map) stack.push(cur_node) while not stack.is_empty(): pop_stack_set_map(stack, l_big_map) for cur_node in reversed(node_list): while (not stack.is_empty() ) and stack.peek().get_value() < cur_node.get_value(): pop_stack_set_map(stack, r_big_map) stack.push(cur_node) while not stack.is_empty(): pop_stack_set_map(stack, r_big_map) head = None for cur_node in node_list: left_big = l_big_map[cur_node] right_big = r_big_map[cur_node] if left_big is None and right_big is None: head = cur_node elif left_big is None: if right_big.left is None: right_big.left = cur_node else: right_big.right = cur_node elif right_big is None: if left_big.left is None: left_big.left = cur_node else: left_big.right = cur_node else: big_node = right_big if left_big.get_value() > right_big.get_value( ) else left_big if big_node.left is None: big_node.left = cur_node else: big_node.right = cur_node return head
def dfs_iter(self, grp, src): vtx = [0] * len(grp) stk = Stack() vtx[src] = 1 stk.push(src) while len(stk) > 0: i = stk.pop() assert (vtx[i] == 1) for j in grp[i]: if vtx[j] == 0: stk.push(i) vtx[j] = 1 stk.push(j) break return vtx
def main(): stack = Stack() stack.push_all([6, 4, 2, 1, 3, 5, 56, 66]) print(stack) # print(get_min2(stack, stack.peek())) # value = get_min(stack) # print(value) # remove(stack, value) # print(stack) # for _ in range(6): # min_value = get_min(stack) # print("min_value:{0}".format(min_value)) # print("stack:{0}".format(stack)) # remove(stack, min_value) # print("stack:{0}".format(stack)) # print("====================") sort(stack)
def get_max_area(height, max_area): stack = Stack() lenght = len(height) j = 0 for index, data in enumerate(height): while(not stack.is_empty()) and height[stack.peek()] >= data: j = stack.pop() k = -1 if stack.is_empty() else stack.peek() max_area = max((index-k-1)*height[j], max_area) stack.push(index) while not stack.is_empty(): j = stack.pop() k = -1 if stack.is_empty() else stack.peek() max_area = max((lenght-k-1)*height[j], max_area) max_area = max(lenght*height[j], max_area) return max_area
def test_stack(self): s = Stack() self.assertEqual(True, s.is_empty()) self.assertEqual(0, s.size()) s.push(1) self.assertEqual(False, s.is_empty()) self.assertEqual(1, s.size()) s.push(True) s.push('Hello,World') self.assertEqual(3, s.size()) self.assertEqual('Hello,World', s.pop()) self.assertEqual(True, s.pop()) s.pop() self.assertEqual(True, s.is_empty())
def bracket_match(self, s): """ :param s: str :return: bool """ dic = {')':'(', '}':'{', ']':'['} stack = Stack() for i in s: if i in {'{', '[', '('}: stack.push(i) else: if stack.get_top() == dic[i]: stack.pop() else: return False if stack.is_empty(): return True else: return False
def test_stack(self): stack = Stack() self.assertEqual(stack.is_empty(), True) self.assertEqual(stack.peek(), None) self.assertEqual(stack._head, None) stack.add_item("first_item") self.assertEqual(stack.peek(), "first_item") stack.add_item("second_item") self.assertEqual(stack.peek(), "second_item") stack.remove_item() self.assertEqual(stack.peek(), "first_item") stack.remove_item() self.assertEqual(stack.is_empty(), True) self.assertEqual(stack.peek(), None) self.assertEqual(stack._head, None)
def dfs(initial, goal_test, successors): frontier = Stack() frontier.push(Node(initial)) explored = {initial} while not frontier.empty: node = frontier.pop() if goal_test(node.state): return node for parent in successors(node.state): if parent in explored: continue explored.add(node.state) frontier.push(Node(parent, node)) return None
def sort_stack(stack): if stack.is_empty(): return stack new_stack = Stack() while not stack.is_empty(): cur = stack.pop() if new_stack.is_empty(): new_stack.push(cur) else: if cur <= new_stack.peek(): new_stack.push(cur) else: while cur > new_stack.peek(): stack.push(new_stack.pop()) if new_stack.is_empty(): new_stack.push(cur) break else: new_stack.push(cur) return new_stack
def isValid(self, s): # unbalance number of parentheses if len(s) % 2 != 0: return False left_parentheses = '([{' right_parentheses = ')]}' stack = Stack() for c in s: # it is not a left parentheses if c in left_parentheses: stack.push(c) # it is a right parentheses elif stack.isEmpty( ) or stack.peek() != left_parentheses[right_parentheses.index(c)]: return False else: stack.pop() return stack.isEmpty()
def infix_to_preifx(expr): """ convert infix to prefix Args: expr: an infix expression in the form of '1 * ( 2 + 3 )'. Returns: An prefix expression. """ # precedence dict prec = {"^": 4, "*": 3, "/": 3, "+": 2, "-": 2, ")": 1} stack = Stack() tokens = expr.split() prefix_expr = deque() # scan from right to left for token in reversed(tokens): # Find a right parenthesis if token == ')': stack.push(token) # Find a left parenthesis elif token == '(': top_token = stack.pop() while top_token != ')': prefix_expr.appendleft(top_token) top_token = stack.pop() # Find an operator elif token in prec: while not stack.isEmpty() and prec[stack.peek()] >= prec[token]: prefix_expr.appendleft(stack.pop()) stack.push(token) # Find an operand else: prefix_expr.appendleft(token) while not stack.isEmpty(): prefix_expr.appendleft(stack.pop()) return " ".join(prefix_expr)
def infix_to_postifx(expr): """ convert infix to postfix Args: expr: an infix expression in the form of '1 * ( 2 + 3 )'. Returns: An postfix expression of the same form. """ # precedence dict prec = {"^": 4, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1} stack = Stack() tokens = expr.split() postfix_expr = [] for token in tokens: # Find a left parenthesis if token == '(': stack.push(token) # Find a right parenthesis elif token == ')': top_token = stack.pop() while top_token != '(': postfix_expr.append(top_token) top_token = stack.pop() # Find an operator elif token in prec: while not stack.isEmpty() and prec[stack.peek()] >= prec[token]: postfix_expr.append(stack.pop()) stack.push(token) # Find an operand else: postfix_expr.append(token) while not stack.isEmpty(): postfix_expr.append(stack.pop()) return " ".join(postfix_expr)
def solution(): init_state = State(3, 3, 1) goal_state = State(0, 0, 0) state_stack = Stack() state_stack.push(init_state) visited = {init_state: True} while not state_stack.is_empty: curr_state = state_stack.pop() for action in actions(): if curr_state.b == 1: new_state = curr_state - action else: new_state = curr_state + action if is_valid_state(new_state) and new_state not in visited: visited[new_state] = True curr_state.next_states.append(new_state) state_stack.push(new_state) if new_state == goal_state: return init_state return []
def generate_randomized_stack(value_range=9, stack_size=10): stack = Stack() for i in range(stack_size): random_int = random.randint(0, value_range) stack.push(random_int) return stack
def setUp(self): self.stack = Stack()
import pathmagic # noqa from data_structure.stack import Stack def delete_middle_from_stack(stack, middle): if stack.size() == middle: stack.pop() return end = stack.pop() delete_middle_from_stack(stack, middle) stack.push(end) if __name__ == "__main__": stack = Stack() arr = [1, 2, 3, 4, 5] for num in arr: stack.push(num) middle = int(stack.size() / 2) + 1 delete_middle_from_stack(stack, middle) stack.show()
def main(): stack = Stack() stack.push_all([2, 6, 1, 87, 2, 33]) new_stack = sort_stack2(stack) print(new_stack)
def __init__(self): self._stack_inp = Stack() # для того чтобы складывать элементы self._stack_out = Stack() # для извлечения элементов self.size = 0