def copy(original_stack): temp_list = [] copied_stock = Stack() for i in original_stack: temp_list.append(i) for i in temp_list[::-1]: copied_stock.push(i) return copied_stock
def parentheses(test_str): s = Stack() for i in test_str: if i in right_parenthesis: s.push(i) else: pop = s.pop() if not ord(pop) - ord(i) <= 2: # 比较ascii数值,小于等于2的话就是匹配的左括号 return False return s.is_empty()
from algs4.Stack import Stack test_str_list = '( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) )'.split() test_stock = Stack() for i in test_str_list: test_stock.push(i) def copy(original_stack): temp_list = [] copied_stock = Stack() for i in original_stack: temp_list.append(i) for i in temp_list[::-1]: copied_stock.push(i) return copied_stock print(copy(test_stock))
def __init__(self): self.__right = Stack() self.__left = Stack() self.__N = 0
from algs4.Stack import Stack test_str = '( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) )' # test_str = '2 * 3 / ( 2 - 1 ) + 3 * ( 4 - 1 )' test_str_list = test_str.split() operator_stack = Stack() numeric_stack = Stack() operator_count = 0 number_count = 0 operator_precedence = {'+': 1, '-': 1, '*': 2, '/': 2} res_str = '' def not_greater(this, peek): try: a = operator_precedence[this] b = operator_precedence[peek] return True if a <= b else False except KeyError: return False for i in test_str_list: if i.isnumeric(): res_str += i + ' ' elif i == '(': operator_stack.push(i) elif i == ')': while not operator_stack.is_empty() and operator_stack.peek() != '(': res_str += operator_stack.pop() + ' ' operator_stack.pop()
from algs4.Stack import Stack test_str = '1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )' test_str_list = test_str.split() res_stack = Stack() num_count = 0 operator_count = 0 for i in test_str_list[::-1]: res_stack.push(i) if i.isnumeric(): num_count += 1 if num_count == 2: num_count = 0 for j in range(operator_count): res_stack.push('(') operator_count = 0 elif i is not ')' and i is not ' ': operator_count += 1 res_str = '' for i in res_stack: res_str += i + ' ' print(res_str)
def __init__(self): self._list_two_stack = [Stack(), Stack()] # self.s1 = Stack() # self.s2 = Stack() self._N = 0