def rpn_calc(postfix_expr): """Evaluate a postfix expression""" operandStack = Stack() tokenList = postfix_expr.split() try: for token in tokenList: if token in "0123456789": operandStack.push(int(token)) elif token in "+-*/": if operandStack.size() < 2: raise StackError("Stack is empty") else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token, operand1, operand2) operandStack.push(result) else: raise TokenError(f"Unknown token: {token}") if operandStack.size() > 1: raise StackError("Stack is not empty") except TokenError as err: raise TokenError(f"{err}") except SyntaxError: raise SyntaxError("Invalid syntax") except StackError as err: raise StackError(f"{err}") else: return operandStack.pop()
def postfix_eval(postfix_expr: str) -> int: """ evaluate postfix expressions in a string """ operandStack = Stack() tokenList = postfix_expr.split() try: for token in tokenList: if token.isnumeric(): operandStack.push(int(token)) elif token in "* ** / // % + -": ## this if statement is not working - why not? if operandStack.size() < 2: raise SyntaxError("invalid syntax") else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = do_math(token, operand1, operand2) operandStack.push(result) elif token == "=": if operandStack.size() > 1: raise StackError("Stack is not empty") elif operandStack.size() == 0: raise StackError("Stack is empty") else: return operandStack.pop() else: raise TokenError(f"Unknown token: {token}") except ZeroDivisionError as err: raise ZeroDivisionError(f"{err}") except SyntaxError: raise SyntaxError(f"Invalid syntax") except TokenError as err: raise TokenError(f"{err}")
def rev_string(my_str): """Reverse characters in a string using a stack""" char_stack = Stack() for char in my_str: char_stack.push(char) new_chars = [] while char_stack.size() > 0: new_chars.append(char_stack.pop()) new_str = "".join(str(char) for char in new_chars) return new_str
def base_converter(dec_num, base): """Convert a decimal number to any base""" digits = "0123456789ABCDEF" remstack = Stack() try: if base in (2, 8, 16): while dec_num > 0: rem = dec_num % base remstack.push(rem) dec_num = dec_num // base new_string = "" ctr = remstack.size() while ctr > 0: new_string = new_string + digits[remstack.pop()] ctr -= 1 return new_string else: raise BaseError except BaseError: print("Invalid base: only 2, 8, or 16 may be used")
print(my_list.size()) print(my_list.search(93)) print(my_list.search(100)) # Alternative implementation from the pythonds3 library # -> sudo pip3 install pythonds3 from pythonds3.basic import Stack s = Stack() print(s.is_empty()) s.push(4) s.push("dog") print(s.peek()) s.push(True) print(s.size()) print(s.is_empty()) s.push(8.4) print(s.pop()) print(s.pop()) print(s.size()) m = Stack() m.push("x") m.push("y") m.push("z") while not m.is_empty(): print(m.peek()) m.pop()