def __init__(self, fpexp): """ 初始化变量,创建栈和树的对象 :param fpexp: 表达式 """ self.fpexp = fpexp self.pStack = Stack() self.eTree = Tree('')
def reverse_string(stack: Stack, input_str: str): for char in input_str: stack.push(char) rev_str = "" while not stack.is_empty(): rev_str += stack.pop() return rev_str
def parChecker(symbolString): """ 简单括号是否匹配 :param symbolString: 括号字符串 :return: bool型,匹配:True,不匹配:False """ # 初始化一个栈 s = Stack() # 是否匹配标志 balanced = True # 下标 index = 0 # 遍历 while index < len(symbolString) and balanced: # 取出字符 symbol = symbolString[index] # 如果为左括号,则入栈 if symbol == '(': s.push(symbol) else: # 当字符不为左括号,如果栈为空,则不匹配 if s.isEmpty(): balanced = False # 如果栈不空,则将左括号出栈 else: s.pop() index = index + 1 if balanced and s.isEmpty(): return True else: return False
def convert_int_to_bin(stack: Stack, dec_num: str): if not dec_num.isnumeric(): return "Please enter a valid string with integer value" dec_num = int(dec_num) if dec_num == 0: return 0 binary_str = "" while dec_num > 0: dec_num, remainder = divmod(dec_num, 2) stack.push(remainder) while not stack.is_empty(): binary_str += str(stack.pop()) return binary_str
def int_to_str(n, base): convert_string = "0123456789" rem_stack = Stack() #Code to push digits onto the stack while n > 0: if n < base: rem_stack.push(n) else: rem_stack.push(n % base) n = n // base #Code to get back the stack values equiv_string = "" while not rem_stack.isEmpty(): equiv_string = equiv_string + convert_string[rem_stack.pop()] return equiv_string if len(equiv_string) > 1 else "0"
def convert_int_to_bin(dec_num): s = Stack() while dec_num > 0: remainder = dec_num % 2 s.push(remainder) dec_num = dec_num // 2 Res = "" while not s.is_empty(): Res += str(s.pop()) return Res
def reverse_polish_notation(self): operands = self.PRIORITIES.keys() OPERATORS = float(self.exprasion) # point stack = Stack() rpn = [] for i in equations: if i == OPERATORS: return rpn if i == operands: return stack while True: if operands in stack: return stack pass
class builderParseTree: """ 利用栈的先进后出特性和树构建解析时并计算 """ def __init__(self, fpexp): """ 初始化变量,创建栈和树的对象 :param fpexp: 表达式 """ self.fpexp = fpexp self.pStack = Stack() self.eTree = Tree('') def builderParseTree(self): """ 构建解析树 :return: 树 """ fplist = self.fpexp.split() self.pStack.push(self.eTree) currentTree = self.eTree for i in fplist: if i == '(': currentTree.insertLeft('') self.pStack.push(currentTree) currentTree = currentTree.getLeftNode() elif i not in '+-*/': currentTree.setRootValue(eval(i)) currentTree = self.pStack.pop() elif i in '+-*/': currentTree.setRootValue(i) currentTree.insertRight('') self.pStack.push(currentTree) currentTree = currentTree.getRightNode() elif i == ')': currentTree = self.pStack.pop() else: raise ValueError("Unknow Operator:" + i) return self.eTree
def baseConberter(decNumber, base): # 定义字符 digits = '0123456789ABCDEF' # 初始化栈 remstack = Stack() while decNumber > 0: rem = decNumber % 2 remstack.push(rem) decNumber = decNumber // base newString = "" while not remstack.isEmpty(): newString = newString + digits[remstack.pop()] return newString
def divideBy2(decNumber): # 初始化栈 remstack = Stack() # 截止条件为被除数大于0 while decNumber > 0: # 取余数 rem = decNumber % 2 # 余数入栈 remstack.push(rem) # 更新被除数 decNumber = decNumber // 2 # 当栈不空的时候,出栈 binString = "" while not remstack.isEmpty(): binString = binString + str(remstack.pop()) return binString
def is_paren_balanced(paren_string): s = Stack() is_balanced = True index = 0 while index < len(paren_string) and is_balanced: paren = paren_string[index] if paren in '({[': s.push(paren) else: if s.is_empty(): is_balanced = False else: top = s.pop() if not is_match(top, paren): is_balanced = False index += 1 if s.is_empty() and is_balanced: return True else: return False
def is_parenthesis_balanced(input_string): stack = Stack() is_balanced = True index = 0 while index < len(input_string) and is_balanced: paren = input_string[index] if paren in "([{": stack.push(paren) else: if stack.is_empty(): is_balanced = False else: top = stack.pop() if not is_match(top, paren): is_balanced = False index += 1 if stack.is_empty() and is_balanced: return True else: return False
def parChecker(symbolString): """ 普通情况:匹配括号(只有括号的符号) :param symbolString: :return: """ s = Stack() balanced = True index = 0 while index < len(symbolString) and balanced: symbol = symbolString[index] if symbol in '( [ {': s.push(symbol) else: if s.isEmpty(): balanced = False else: top = s.pop() if not matches(top, symbol): # false balanced = False index += 1 return True if s.isEmpty() and not balanced else False
class transition: def __init__(self): self.stack = Stack() self.base_str = "" def toStr(self, num, base): """ 使用栈帧递归将任何数转换成进制数 :param num: 转换的数 :param base: 进制数 :return: 转换之后的数 """ coverString = "0123456789ABCDEF" if num < base: self.stack.push(coverString[num]) else: self.stack.push(coverString[num % base]) self.toStr(num//base, base) def show(self): for i in range(self.stack.size()): self.base_str += self.stack.pop() print(self.base_str)
def create_Target(): """ 生成Strack的对象 :return:Strack的对象 """ return Stack()
from Stack.stack import Stack obj = Stack() obj.push(1) obj.push(2) while obj.isEmpty() is False: print(obj.pops())
from Stack.stack import Stack def reverse_string(s1, s): for i in range(len(s)): s1.push(s[i]) rev_str = "" while not s1.is_empty(): rev_str += s1.pop() return rev_str if __name__ == '__main__': s1 = Stack() s = "!evitacudE ot emocleW" print(reverse_string(s1, s))
def infixToPostfix(infixexpr): # 记录操作符优先级 prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 # 初始化栈 opStack = Stack() postfixList = [] # 将表达式转为单词列表 tokenList = infixexpr.split() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = 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()) return " ".join(postfixList)
def stack_calculate(list_suffix): stack = Stack() if not isinstance(list_suffix, list): return 'list of suffix error' for i in list_suffix: if is_number(i): stack.stack_push(i) elif i in ( '+', '-', '*', '/', ): pop_1 = stack.stack_pop() pop_2 = stack.stack_pop() if i in ('-', '/'): stack.stack_push(pop_2 - pop_1) if i == '-' else stack.stack_push( pop_2 / pop_1) else: stack.stack_push(pop_2 + pop_1) if i == '+' else stack.stack_push( pop_2 * pop_1) return stack.stack_show()
def main(): s = Stack() s.push(data=5) s.push(data=10) s.push(data=15) s.__str__()
# Importing my File Created With a class named Stack from Stack.stack import Stack # Main Function. if __name__ == "__main__": # Creating a Stack Object stack = Stack() # Going into a While loop till user tells to stop while True: # Printing out all the Operations print("STACK OPERATIONS") print("1. Push") print("2. Pop") print("3. Peek") print("4. Display Stack") print("5. Exit") # Taking the Choice ch = int(input("Enter Your Choice(1-5): ")) # Creating A switch statement in python if ch == 1: # Taking the item to push item = int(input("Enter item: ")) # Pushing the item stack.Push(item) elif ch == 2: # Poping an item item = stack.Pop() # checking for Underflow if item == "Underflow": print("Underflow, stack is Empty!!") else: print("Popped item is", item)
def __init__(self): self.stack = Stack() self.base_str = ""
print(stack.peek()) def option_exit(stack): del stack print("THANK YOU !!! HAVE A GREAT DAY !!!") quit(1) def option_size(stack): print(stack.size()) if __name__ == '__main__': user_input = "y" stack = Stack() print("~" * 10, "STACK", "~" * 10) print("Enter p to POP, s for SIZE, v to VIEW TOP, q to QUIT") while user_input != "0": try: user_input = input("Enter item to store >>> ") if user_input == "p": option_pop(stack) elif user_input == "s": option_size(stack) elif user_input == "v": option_peek(stack) elif user_input == "q": option_exit(stack) else: option_push(stack, user_input)
def infixToPostfix(infixexpr): opstack = Stack() # 创建空栈 result = [] # 结果的列表 prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1} # 运算符的优先级 operator_list = ['+', '-', '*', '/'] for token in tolist(infixexpr): if token.capitalize() in string.ascii_uppercase: # 判断是否是操作数 result.append(token.capitalize()) else: if token == '(': # 判断是是否是左括号 opstack.push(token) elif token == ')': # 判断是否是右括号 topToken = opstack.pop() while topToken != '(': result.append(topToken) topToken = opstack.pop() elif token in operator_list: # 判断是否是运算符 while not opstack.isEmpty() and (prec[opstack.peek()] >= prec[token]): result.append(opstack.pop()) opstack.push(token) else: pass while not opstack.isEmpty(): result.append(opstack.pop()) return "".join(result)