def parChecker(symbol_string): """ 先写一个只有'()'类型的算法 @symbol_string: 要匹配的括号字符串 @return: 返回匹配结果,bool类型 """ stack = Stack() index = 0 balanced_flag = True # 两边括号数量平衡标识 while index < len(symbol_string) and balanced_flag: symbol = symbol_string[index] if symbol == '(': stack.push(symbol) else: if stack.isEmpty(): balanced_flag = False else: stack.pop() index += 1 if balanced_flag and stack.isEmpty(): balanced_flag = True else: balanced_flag = False return balanced_flag
def infixToPostfix(infixExpr): """ 中缀表达式转后缀表达式算法实现 @infixExpr: 中缀表达式,格式如:A + B * C,必须含空格,且操作数只包含A-Z 0-9其中的值 @return: 转换成功的后缀表达式 """ # 记录操作符优先级 prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 op_stack = Stack() possible_str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' post_fix_lst = [] token_lst = infixExpr.split() for token in token_lst: # 如果单词是 操作数, 则直接添加到后缀表达式列表的末尾 if token in possible_str: post_fix_lst.append(token) # 如果单词是左'(', 则压入栈顶,标记下 elif token == '(': op_stack.push(token) # 如果单词是右')',则反复弹出栈顶操作符,加入到输出列表末尾,直到遇到左括号 elif token == ')': top_token = op_stack.pop() while top_token != '(': post_fix_lst.append(top_token) top_token = op_stack.pop() # 如果单词是操作符, 则压入栈顶, # 但在压之前, 要比较其与栈顶操作符的优先级 # 如果栈顶操作符的优先级高于它, 就要反复弹出栈顶操作符, 加入到输出列表末尾 # 直到栈顶操作符的优先级低于它 else: # 注意条件prec[op_stack.peek()] >= prec[token], 不是 > ,是 >=,因为+- 或*/是同一级 while (not op_stack.isEmpty()) and (prec[op_stack.peek()] >= prec[token]): post_fix_lst.append(op_stack.pop()) op_stack.push(token) # 扫描结束后,把opstack栈中的所有剩余操作符依次弹出,加入到输出列表末尾 # 把输出列表再用join()合并成后缀表达式字符串 while not op_stack.isEmpty(): post_fix_lst.append(op_stack.pop()) return " ".join(post_fix_lst)
def express_convert(text): '''将中缀表达式转换成后缀表达式 看懂算法的前提是了解中缀表达式转换后缀表达式的过程; 明确表达式包含的元素:1)操作数,这里将操作数抽象为a-z,即26个小写字母集合; 2)操作符,+-*/,+-同等优先级,*/同等优先级并且优先级高于+- 3)小括号。小括号内的表达式要先算 示例: a + b + c ==> ab+c+ a + b * c ==> abc*+ a * (b + c) ==> abc+* a + (b + c) * d == > a b c + d * + 算法流程: 0)用result_list存储结果 1)遇操作数,将其append进result_list 2)遇操作符,如栈内无元素,入栈; 如栈内有元素,与栈顶元素比较优先级;比栈顶优先级高,则入栈,小于或等于,则弹出栈顶元素并append到result_list,再入 3)遇左括号,入栈; 4)遇右括号,不断弹出栈顶操作符,直至弹出左括号。 :param text: str, 中缀表达式 :return: str, 后缀表达式 ''' text = text.replace(' ', '') result_list = [] stack = Stack() priority = {'(': 1, '*': 2, '/': 2, '+': 3, '-': 3} for i in text: if i in 'abcdefghijklmnopqrstuvwxyz': result_list.append(i) elif i in '+-*/(': if not stack.is_empty(): top_item = stack.get_top() if top_item != '(' and priority[i] >= priority[top_item]: item = stack.pop() result_list.append(item) stack.push(i) # print(stack.get_items()) elif i in ')': while True: item = stack.pop() if item == '(': break result_list.append(item) while not stack.is_empty(): item = stack.pop() result_list.append(item) return ' '.join(result_list)
def par_checker(text): ''' 括号匹配,这里只考虑大、中、小括号。 算法思路很简单,从左到右遍历文本,左括入栈,遇右括出栈,出栈时检查匹配与否;遍历完检索栈内是否还有元素 :param text: 输入文本 :return: True or False ''' result = True stack = Stack() left_par = '([{' right_par = {')': '(', ']': '[', '}': '{'} for i in text: if i in left_par: stack.push(i) if i in right_par.keys(): if stack.is_empty(): result = False break pop_item = stack.pop() if pop_item != right_par[i]: result = False break if not stack.is_empty(): result = False return result
def decimal_convert(num, convert_to=2): '''将十进制数转换成其它进制数,以字符串返回 算法思路就是用十进制数除以N(进制),取余,直至结果为0。最后的余数为新进制数的最高位,符合栈的后进先出特点,故用栈存储余数。 :param num: int, 十进制数字 :param convert_to: int, 要转换的进制 :return: str, 转换后的数字 ''' if not num: return '0' stack = Stack() # 这个技巧非常漂亮。将余数的数字与字母对应起来(十六进制场景) ch = '0123456789ABCDEF' while num // convert_to: item = num % convert_to num = num // convert_to stack.push(item) if num: stack.push(num) res = '' while not stack.is_empty(): res += str(ch[stack.pop()]) return res
def parCheckerMore(symbol_string): """ 通用括号匹配,支持 (, [, { 这三种 @symbol_string: 要匹配的括号字符串 @return: 返回匹配结果,bool类型 """ stack = Stack() index = 0 balanced_flag = True # 两边括号数量平衡标识 while index < len(symbol_string) and balanced_flag: symbol = symbol_string[index] # 判断左边括号类型需要调整 if symbol in '([{': stack.push(symbol) else: if stack.isEmpty(): balanced_flag = False else: top = stack.pop() # 栈中移除的括号要和进入栈的括号匹配类型 if not matches(top, symbol): balanced_flag = False index += 1 if balanced_flag and stack.isEmpty(): balanced_flag = True else: balanced_flag = False return balanced_flag
def convert_to_base(self, base): decimal = self.a s = Stack() while decimal > 0: decimal, remender = divmod(decimal, base) s.push(remender) n = "" while not s.isEmpty(): n += Digit.digits[s.pop()] self.a = n
def postfixEval(postfixExpr): """ 后缀表达式求值 @postfixExpr: 后缀表达式 @return: 计算结果 """ token_lst = postfixExpr.split() operand_stack = Stack() for token in token_lst: # 如果是操作数,则压入栈顶 if token in '123456789': operand_stack.push(int(token)) # 否则取操作数开始计算 else: # 栈的特性,后进先出 operand2 = operand_stack.pop() operand1 = operand_stack.pop() result = math_eval(token, operand1, operand2) operand_stack.push(result) return operand_stack.pop()
def divideBy2(decNumber): """ 10进制数转2进制 @num: 需要转换的数 @return: 转换后的结果 """ remainder_stack = Stack() while decNumber > 0: remainder = decNumber % 2 remainder_stack.push(remainder) decNumber //= 2 # 整除 result = '' while not remainder_stack.isEmpty(): result += str(remainder_stack.pop()) return result
class PreorderIteratorStack: def __init__(self, root): self.current = None self.stack = Stack(1000) self.stack.push(root) def __iter__(self): return self def __next__(self): if self.stack.is_empty(): raise StopIteration current = self.stack.pop() if current.right is not None: self.stack.push(current.right) if current.left is not None: self.stack.push(current.left) return current.item
def baseConvert(decNumber, base): """ 10进制数转成任意16进制以下的数 @decNumber: 需要转换的数 @base: 进制 @return: 转换后的结果 """ digits = '0123456789ABCDEF' # 定义数范围(最大16进制) remainder_stack = Stack() while decNumber > 0: remainder = decNumber % base remainder_stack.push(remainder) decNumber //= base # 整除 result = '' while not remainder_stack.isEmpty(): result += digits[remainder_stack.pop()] return result
def dfs(gui, one_step=False): starting_pos = gui.grid.head.get_node() fringe = Stack() # Fringe holds a list of tuples: (node position, move to get prev to current, cost) fringe.push([(starting_pos, None, 0)]) path = [] visited = [starting_pos] while not fringe.is_empty(): # Get the next one to be popped off the stack to search it's neighbor nodes (successors) path = fringe.pop() visited.append(path[-1][0]) if gui.grid.grid[path[-1][0][0]][path[-1][0][1]] == 3: break for neighbor in get_neighbors(gui, path[-1][0][0], path[-1][0][1]): if neighbor[0] not in visited: updated_path = copy.copy(path) updated_path.append(neighbor) fringe.push(updated_path) if not fringe.is_empty(): move_set = [] while path: temp = path.pop(0) if temp[1] is not None: move_set.append(temp[1]) if not one_step: return move_set else: return [move_set[0]] else: no_dfs_move = go_furthest(gui) if no_dfs_move: return no_dfs_move else: no_moves_at_all = go_down() return no_moves_at_all
queue.add(7) print("the data structure is of size: " + str(queue.get_size())) print(queue.remove()) print(queue.remove()) print(queue.remove()) print(queue.remove()) print("the data structure is of size: " + str(queue.get_size())) print("\nTESTING STACK WITH ARRAYS\n") stack = Stack("array") stack.push(2) stack.push(4) stack.push(7) print("the data structure is of size: " + str(stack.get_size())) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop()) print("the data structure is of size: " + str(stack.get_size())) print("\nTESTING QUEUE WITH LINKED_LIST\n") queue = Queue("linked") queue.add(2) queue.add(4) queue.add(7) print("the data structure is of size: " + str(queue.get_size())) print(queue.remove()) print(queue.remove()) print(queue.remove())