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.
Python Implement function swapFL() that takes a list as input and swaps the first and last...
Python Implement function swapFL() that takes a list as input and swaps the first and last ele- ments of the list. You may assume the list will be nonempty. The function should return the new list. >>> ingredients = ['flour', 'sugar', 'butter', 'apples'] >>> swapFL(ingredients) >>> ingredients ['apples', 'sugar', 'butter', 'flour']
Using Python, Implement a decryption function: Implement a function named decrypt that opens a file named...
Using Python, Implement a decryption function: Implement a function named decrypt that opens a file named input_file and decrypts its content using the opposite of the dictionary created using a key (which is a parameter of the function) and stores the decrypted file to a file named output_file. The input and output file names will be positional parameters. The key parameter should be a keyword-only optional parameter where the default value is “IT RAINS A LOT IN MILWAUKEE IN THE...
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 Implement function allEven() that takes a list of integers and returns True if all integers...
Python Implement function allEven() that takes a list of integers and returns True if all integers in the list are even, and False otherwise. >>> allEven([8, 0, -2, 4, -6, 10]) True >>> allEven([8, 0, -1, 4, -6, 10]) False
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
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]     """
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT