Question

In: Computer Science

Implement in Python using stack operations. Postfix Calculator Post fix calculator • We use a stack...

Implement in Python using stack operations.

Postfix Calculator

Post fix calculator


• We use a stack
• When an operand is read, push it on statck
• When an operator is read i.e +, *. /, -
– Pop two from the top of the stack and apply the operator and push the result on stack
if there is one value instead of two display an error message

• Keep repeating until an equal sign, = is read; pop from the top of stack and stop.

Postfix Expression          Result

4 5 7 2 + - * = -16 ===> (5 - (7 + 2 ) )* 4 = -16

3 4 + 2  * 7 / = 2

5 7 + 6 2 -  * = 48

4 2 3 5 1 - + * + = 18 ===> (5-1 + 3 ) * 2 + 4 = 18

List as Stack

"""

File: pyStackPostfix.py

Author: JD

"""

# 5 7 + 6 2 -  * = 48

print("Postfix Calculator\n")

stack = []              # Empty stack

y = int(0)

z = int(0)

w = int(0)

while True:

   x = input("Enter a postfix expression one by one:")

   if x >= '0' and x<= '9':

      x = int(x)

      stack.append(x)      # Push on top of stack

   elif x == '+':          # Got an operator

      if len(stack) >= 2:

         y = stack.pop()   # Pop from top of stack

         z = stack.pop()

         w = y + z

         stack.append(w)   # Push result back

      else:

         print("Stack error") # Not enough operhand A + B

         break

   elif x == '-':

      if len(stack) >= 2:

         y = stack.pop()

         z = stack.pop()

         w = y - z

         stack.append(w)  

      else:

         print("Stack error")

         break

   elif x == '*':

      if len(stack) >= 2:

         y = stack.pop()

         z = stack.pop()

         w = y * z

         stack.append(w)  

      else:

         print("Stack error")

         break

   elif x == '/':

      if len(stack) >= 2:

         y = stack.pop()

         z = stack.pop()

         w = y / z

         stack.append(w)  

      else:

         print("Stack error")

         break

   elif x == '=':             # Equal operator

      if len(stack) == 1:

         z = stack.pop()      # Pop the result

         print (z)

         break

      else:

         print("Stack error")

         break

IN PYTON

Solutions

Expert Solution

You just need to change the order of opertors in operations, i.e use z - y instead of y - z. Also you can input full experssion in one line.

"""
File: pyStackPostfix.py
Author: JD
"""
# 5 7 + 6 2 -  * = 48

print("Postfix Calculator\n")

stack = []              # Empty stack
y = int(0)
z = int(0)
w = int(0)

# expression list
exp = input("Enter a postfix expression:").split()

for x in exp:
  if x >= '0' and x<= '9':
      x = int(x)
      stack.append(x)      # Push on top of stack

  elif x == '+':          # Got an operator
      if len(stack) >= 2:
        y = stack.pop()   # Pop from top of stack
        z = stack.pop()
        w = z + y
        stack.append(w)   # Push result back
      else:
        print("Stack error") # Not enough operhand A + B
        break

  elif x == '-':
      if len(stack) >= 2:
        y = stack.pop()
        z = stack.pop()
        w = z - y
        stack.append(w)  
      else:
        print("Stack error")
        break

  elif x == '*':
      if len(stack) >= 2:
        y = stack.pop()
        z = stack.pop()
        w = z * y
        stack.append(w)  
      else:
        print("Stack error")
        break

  elif x == '/':
      if len(stack) >= 2:
        y = stack.pop()
        z = stack.pop()
        w = z / y
        stack.append(w)  
      else:
        print("Stack error")
        break

  elif x == '=':             # Equal operator
      if len(stack) == 1:
        z = stack.pop()      # Pop the result
        print(z)
        break

      else:
        print("Stack error")
        break

Related Solutions

Create: post fix calculator By Using: stack concept LinkedList is original line Queue is the waitlist...
Create: post fix calculator By Using: stack concept LinkedList is original line Queue is the waitlist Requirements - Orchestra passes are on sale. Enter first names of the people to form the line. Assume there is certain criteria that will have to be checked before purchase of passes (must be an annual ticket holder to purchase pass). You will have to eliminate those not meeting it from the line. A lottery will be done and the outcome will insert that...
Write a code to implement a python stack class using linked list. use these operations isEmpty...
Write a code to implement a python stack class using linked list. use these operations isEmpty   • push. • pop.   • peek. • size Time and compare the performances ( this is optional but I would appreciate it)
Using STL stack class, implement in C++ a function that converts an infix expression to postfix...
Using STL stack class, implement in C++ a function that converts an infix expression to postfix expression,
Postfix Arithmetic Operation (C++) Friday, 27 September 2019, 04:21 PM Use stack to implement postfix arithmetic...
Postfix Arithmetic Operation (C++) Friday, 27 September 2019, 04:21 PM Use stack to implement postfix arithmetic operation. Input Many test cases until EOF. Each line is a postfix arithmetic operation formula. There is no blank between the numbers, and the number only is 0-9. Output The result of each line. But if the postfix arithmetic operation formula is wrong (it means you can't get the correct answer), please output "Input Error". Sample Input 35+ 3+5 63/14-*3+8- Sample Output 8 Input...
Implement a calculator (not postfix notation) using Swift Programming Language(Swift 3, basic ios app). Please use...
Implement a calculator (not postfix notation) using Swift Programming Language(Swift 3, basic ios app). Please use MVC model(CalculatorBrain.swift can be the model and ViewController.swift can be the view). Also please post the sreenshot of the storyboard that you make. Requirements: Implement add subtract, multiply, divide, pi, sqrt, Euler’s natural number (e), co-sine and equals. Ensure you have the ability to handle multiple operations in sequence Implement the ability to enter floating point numbers into the display Add 4 more buttons...
Write a java class program to convert from INFIX TO POSTFIX Using stack operations
Write a java class program to convert from INFIX TO POSTFIX Using stack operations
Write a code to implement a python queue class using a linked list. use these operations...
Write a code to implement a python queue class using a linked list. use these operations isEmpty • enqueue. • dequeue    • size Time and compare the performances of the operations ( this is optional but I would appreciate it)
Implement the stack class (called Stack2) using queue, meaning that the only operations that can be...
Implement the stack class (called Stack2) using queue, meaning that the only operations that can be used are the ones defined in the Queue class. class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0, item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) The codes to fill: """ 1. Stack2 class Implement stack data structure using queue """ class Stack2: def __init__(self): # Write your definition for __init__ here def isEmpty(self): #...
All code should be in Python 3. Implement the Stack Class, using the push, pop, str,...
All code should be in Python 3. Implement the Stack Class, using the push, pop, str, init methods, and the insurance variable 'list'.
IN JAVA LANGUAGE Linked List-Based Stack Implementation Implement Stack using a Linked List Use the language...
IN JAVA LANGUAGE Linked List-Based Stack Implementation Implement Stack using a Linked List Use the language library LinkedList Stack methods will call the LinkedList methods You can use string as the object Instead of using an array, as the StackLab did, here you will use a Linked List from your language's library. Implement all the methods of Stack : push(), pop(), size(), printStackDown(), etc, using calls to the linked list methods that correspond to the actions need. In the array...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT