Question

In python: using a stack, implement a function that takes in an arithmetic expression, and evaluates...

In python: using a stack, implement a function that takes in an arithmetic expression, and evaluates it, supported operations are + and -, which have same precedence. .

Homework Answers

Answer #1

class Stack:
  
 
  def __init__(self):
    self.stack = []
  
  # push into stack
  def push(self, data):
    if data not in self.stack:
      self.stack.append(data)
      return True
    else:
      return False
    [r]
  # remove the top element
  def pop(self):
    if len(self.stack) <= 0:
      return "Stack is empty!"
    else:
      return self.stack.pop()
    
  # returns the size of the element
  def size(self):
    return len(self.stack)
    
  # peek to see the top element
  def peek(self):
    return self.stack[-1]
    
  # to check if stck is empty
  def isEmpty(self):
    if len(self.stack) <= 0:
      return True
    else:
      return False
  
  # show the content of stack
  def show(self):
    return self.stack

def applyOp(op, var2, var1):
  if op == '+':
    return int(var1) + int(var2)
  elif op == '-':
    return int(var1) - int(var2)
  else:
    return 0

# check for precedence of operators
# returns True if op2 has higher precedence than op1
def hasPrecedence(op1, op2):
  if op2 == '(' or op2 == ')':
    return False
  elif (op2 == '+' or op2 == '-'):
    return False
  else:
    return True


expr = raw_input("Enter the expression:")


tokens = map(str, expr)

tokens = ' '.join(tokens).split()


var = Stack()

ops = Stack()

skip = 0
for i in range(len(tokens)):

  if skip >= 1:
    
    skip -= 1
    continue

  if tokens[i] >= '0' and tokens[i] <= '9':
    num = tokens[i]
    
    for j in range(i+1, len(tokens)):
      if tokens[j] >= '0' and tokens[j] <= '9':
        num = num + tokens[j]
        skip += 1
      else:
        break
    
    var.push(num)
    print(var.show())
  
 
  elif tokens[i] == '(':
    
    ops.push(tokens[i])
  
  
  elif tokens[i] == ')':
    print("Encountered closing parenthesis...")
    while ops.peek() != '(':
      
      value = applyOp(ops.pop(), var.pop(), var.pop())
      if(value == "infinity"):
        print("Invalid Expression")
        break
      else:
        print(value)
        var.push(value)
    ops.pop()
  
  elif tokens[i] in ('+','-'):
    while ops.isEmpty() is False and hasPrecedence(tokens[i], ops.peek()):
      x = applyOp(ops.pop(), var.pop(), var.pop())
      print(x)
      var.push(x)
  
    ops.push(tokens[i])
    print(ops.show())

while(ops.isEmpty() is False):
  var.push(applyOp(ops.pop(), var.pop(), var.pop()))
print("Result of the expression is " + str(var.pop()))
Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
For the below Python expression: Evaluate the expression Show the PROCESS for how Python evaluates the...
For the below Python expression: Evaluate the expression Show the PROCESS for how Python evaluates the expression (order of operations and showing the steps Python takes to evaluate the problem).   3 % 3 * 14 == 18.2 / 8.1 and 3.1 + 15.7 * 19.1 >= 6.6 // 18 // 15.0
(For Python) Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression...
(For Python) Evaluating Postfix Arithmetic Expressions. In this project you are to implement a Postfix Expression Evaluator as described in section 7-3b of the book. The program should ask the user for a string that contains a Postfix Expression. It should then use the string's split function to create a list with each token in the expression stored as items in the list. Now, using either the stack classes from 7.2 or using the simulated stack functionality available in a...
Function which takes a string and uses a stack to calculate the value of theequation passed...
Function which takes a string and uses a stack to calculate the value of theequation passed in. This equation is assumed to be in postfix/reverse Polishnotation. RETURNS: The value that the equation evaluates to using postfix notation python please :)
Write a C++ function that takes in an arithmetic expression in prefix notation and converts it...
Write a C++ function that takes in an arithmetic expression in prefix notation and converts it into a binary tree, such that each operation is stored in a node whose left subtree stores the left operand, and whose right subtree stores the right operand.
In Python, implement a function that takes in two sorted lists and merges them into one...
In Python, implement a function that takes in two sorted lists and merges them into one list, the new list must be sorted. The function MUST run in O(m+n), where m is the length of list 1 and n the length of list 2. In other words, the function cannot do more than one pass on list 1 and list 2.
Python Mutable Sequences Implement a function reverse that takes a list as an argument and reverses...
Python Mutable Sequences Implement a function reverse that takes a list as an argument and reverses the list. You should mutate the original list, without creating any new lists. Do NOT return anything. Do not use any built-in list functions such as reverse(). def reverse(lst):    """Reverses lst in place (i.e. doesn't create new lists).     >>> L = [1, 2, 3, 4]     >>> reverse(L)     >>> L     [4, 3, 2, 1]     """
In five sentences describe the following: a) how you would implement a stack using an array,...
In five sentences describe the following: a) how you would implement a stack using an array, including the push and pop operation b) how you could implement a queue using a linked list, including what type of linked list would be best, the enqueue and dequeue operations
in Java In this exercise, you'll write a Java version of the infix-to-postfix conversion algorithm. These...
in Java In this exercise, you'll write a Java version of the infix-to-postfix conversion algorithm. These same mechanisms can be used as a part of writing a simple compiler. Write class InfixToPostfixConverter co convert an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers (to make things easier) such as (6 + 2) • 5 - 8 / 4 to a postfix expression. The postfix version (no parentheses are needed) of this infix expression is 6...
C++ Using the Stack operations, write a pseudocode routine, dupA, that takes aStack for string, checks...
C++ Using the Stack operations, write a pseudocode routine, dupA, that takes aStack for string, checks to see if the top starts with ‘A’ or ‘a’. If so, duplicate the top of the stack (i.e. pop a copy of that value onto the stack) else if length > 10, pop it off the stack
Python 3 Implement the function invert_and_merge, which takes any number of input dictionaries via a star...
Python 3 Implement the function invert_and_merge, which takes any number of input dictionaries via a star parameter, and inverts and merges them into a single result dictionary. When inverting a dictionary, the keys and values are flipped, so that each value maps to a set containing the corresponding key(s) in the original dictionary. When merging the inverted dictionaries, sets corresponding to the same key are combined. Examples: invert_and_merge({'a': 1, 'b': 2, 'c': 1, 'd': 1, 'e': 2}) should return {1:...