def postfix_converter(infixstring): op_stack = Stack() output_list = [] infix_list = infixstring.split(' ') operators = '*/+-' for char in infix_list: if char == '(': op_stack.push(char) elif char == ')': prior_op = op_stack.pop() while prior_op != '(': output_list.append(prior_op) prior_op = op_stack.pop() elif char in operators: if op_stack.contains_items() and op_stack.peek() in '*/': output_list.append(op_stack.pop()) op_stack.push(char) else: op_stack.push(char) else: output_list.append(char) while op_stack.contains_items(): output_list.append(op_stack.pop()) return " ".join(output_list)
def paren_checker(string): stack = Stack() for char in string: if char == '(': stack.push(char) elif char == ')': if stack.contains_items(): stack.pop() else: return 'Unbalanced' if stack.contains_items(): return 'Unbalanced' else: return 'Balanced'
def general_checker(string): stack = Stack() opens = '([{<' closes = ')]}>' for char in string: if char in opens: stack.push(char) elif char in closes: if not stack.contains_items(): return "Stack prematurely empty. Unbalanced." else: prior = stack.pop() return match_checker(char, prior) # returns Balanced or Unbalanced if stack.contains_items(): return 'Unbalanced' else: return 'Balanced'
def int_to_bin(value): stack = Stack() num = int(value) binary_num = '' while num > 0: stack.push(num % 2) num //= 2 while stack.contains_items(): binary_num += str(stack.pop()) return binary_num
def base_converter(): stack = Stack() digits = '0123456789ABCDEF' num = int(raw_input('Enter a number in base-10 to convert: ')) base = int(raw_input('Enter a base to convert it to: ')) new_num = '' while num > 0: stack.push(num % base) num //= base while stack.contains_items(): new_num += str(digits[stack.pop()]) print new_num
def base_converter(): stack = Stack() digits = '0123456789ABCDEF' num = int(raw_input('Enter a number to convert: ')) base = int(raw_input('Enter a base to convert to: ')) new_num = '' while num > 0: stack.push(num % base) num //= base while stack.contains_items(): new_num += str(digits[stack.pop()]) return new_num
def base_converter(): stack = Stack() digits = "0123456789ABCDEF" num = int(raw_input("Enter a number in base-10 to convert: ")) base = int(raw_input("Enter a base to convert it to: ")) new_num = "" while num > 0: stack.push(num % base) num //= base while stack.contains_items(): new_num += str(digits[stack.pop()]) print new_num