Question

In: Computer Science

1. Please program the following in Python 3 code. 2. Please share your code. 3. Please...

1. Please program the following in Python 3 code.

2. Please share your code.

3. Please show all outputs.

Instructions:

Run Python code  List as Stack  and verify the following calculations; submit screen shots in a single file.

Postfix Expression                Result

4 5 7 2 + - * = -16

3 4 + 2  * 7 / = 2

5 7 + 6 2 -  * = 48

4 2 3 5 1 - + * + = 18  

List as Stack Code:

""" 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

Postfix Calculator

Enter a postfix expression one by one:5
Enter a postfix expression one by one:7
Enter a postfix expression one by one:+
Enter a postfix expression one by one:6
Enter a postfix expression one by one:2
Enter a postfix expression one by one:-
Enter a postfix expression one by one:*
Enter a postfix expression one by one:=
48
Press any key to continue . . .

Solutions

Expert Solution

# Class to convert the expression
class Evaluate:
  
# Constructor to initialize the class variables
def __init__(self, capacity):
self.top = -1 #declare top of stack
self.capacity = capacity
# This array is used a stack
self.array = []
  
# check if the stack is empty
def isEmpty(self):
return True if self.top == -1 else False
  
# Return the value of the top of the stack
def peek(self):
return self.array[-1]
  
# Pop the element from the stack
def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"
  
# Push the element to the stack
def push(self, op):
self.top += 1
self.array.append(op)
  
  
# The main function that converts given infix expression
# to postfix expression
def evaluatePostfix(self, exp):
  
# Iterate over the expression for conversion
for i in exp:
  
# If the scanned character is an operand
# (number here) push it to the stack
if i.isdigit():
self.push(i)
  
# If the scanned character is an operator,
# pop two elements from stack and apply it.
else:
val1 = self.pop()
val2 = self.pop()
self.push(str(eval(val2 + i + val1)))
  
return int(self.pop())
  
  
  
# Driver program to test above function
exp=[] #temporary list to store expression
ele=input('Enter element of postfix expression: ') #asking for first element of expression
while ele is not '=': #check if input is '=' if yes then stop asking for next element
   exp.append(ele)
   ele=input('Enter element of postfix expression: ')

obj = Evaluate(len(exp)) #evaluate expression
print("postfix evaluation: ",(obj.evaluatePostfix(exp))) #print the result

Save the above program using .py extension and run it using python 3

screenshots of your expressions are attached below

Thank you!


Related Solutions

Please provide Python code that does the following: 3) Write a program that takes a string...
Please provide Python code that does the following: 3) Write a program that takes a string as input, checks to see if it is comprised entirely of letters, and if all those letters are lower case. The output should be one of three possible messages: Your string is comprised entirely of lower case letters. Your string is comprised entirely of letters but some or all are upper case. Your string is not comprised entirely of letters. Your program may NOT:...
Please write in beginner level PYTHON code! Your job is to write a Python program that...
Please write in beginner level PYTHON code! Your job is to write a Python program that asks the user to make one of two choices: destruct or construct. - If the user chooses to destruct, prompt them for an alternade, and then output the 2 words from that alternade. - If the user chooses construct, prompt them for 2 words, and then output the alternade that would have produced those words. - You must enforce that the users enter real...
Please write in Python code Write a program that stores the following data in a tuple:...
Please write in Python code Write a program that stores the following data in a tuple: 54,76,32,14,29,12,64,97,50,86,43,12 The program needs to display a menu to the user, with the following 4 options: 1 – Display minimum 2 – Display maximum 3 – Display total 4 – Display average 5 – Quit Make your program loop back to this menu until the user chooses option 5. Write code for all 4 other menu choices
(CODE IN PYTHON) Program Input: Your program will display a welcome message to the user and...
(CODE IN PYTHON) Program Input: Your program will display a welcome message to the user and a menu of options for the user to choose from. Welcome to the Email Analyzer program. Please choose from the following options: Upload text data Find by Receiver Download statistics Exit the program Program Options Option 1: Upload Text Data If the user chooses this option, the program will Prompt the user for the file that contains the data. Read in the records in...
Please add to this Python, Guess My Number Program. Add code to the program to make...
Please add to this Python, Guess My Number Program. Add code to the program to make it ask the user for his/her name and then greet that user by their name. Please add code comments throughout the rest of the program If possible or where you add in the code to make it ask the name and greet them before the program begins. import random def menu(): print("\n\n1. You guess the number\n2. You type a number and see if the...
Please write in Python code please: Write a program that asks the user to enter 5...
Please write in Python code please: Write a program that asks the user to enter 5 test scores between 0 and 100. The program should display a letter grade for each score and the average test score. You will need to write the following functions, including main: calc_average – The function should accept a list of 5 test scores as an input argument, and return the average of the scores determine_grade – The function should accept a test score as...
Python Explain Code #Python program class TreeNode:
Python Explain Code   #Python program class TreeNode:    def __init__(self, key):        self.key = key        self.left = None        self.right = Nonedef findMaxDifference(root, diff=float('-inf')):    if root is None:        return float('inf'), diff    leftVal, diff = findMaxDifference(root.left, diff)    rightVal, diff = findMaxDifference(root.right, diff)    currentDiff = root.key - min(leftVal, rightVal)    diff = max(diff, currentDiff)     return min(min(leftVal, rightVal), root.key), diff root = TreeNode(6)root.left = TreeNode(3)root.right = TreeNode(8)root.right.left = TreeNode(2)root.right.right = TreeNode(4)root.right.left.left = TreeNode(1)root.right.left.right = TreeNode(7)print(findMaxDifference(root)[1])
The code that creates this program using Python: Your program must include: You will generate a...
The code that creates this program using Python: Your program must include: You will generate a random number between 1 and 100 You will repeatedly ask the user to guess a number between 1 and 100 until they guess the random number. When their guess is too high – let them know When their guess is too low – let them know If they use more than 5 guesses, tell them they lose, you only get 5 guesses. And stop...
a) write a python programme for converting url.to html please provide valid code and please share...
a) write a python programme for converting url.to html please provide valid code and please share screenshots to me
Please write in Python code please Write a program that creates a dictionary containing course numbers...
Please write in Python code please Write a program that creates a dictionary containing course numbers and the room numbers of the rooms where the courses meet. The dictionary should have the following key-value pairs: Course Number (key) Room Number (value) CS101 3004 CS102 4501 CS103 6755 NT110 1244 CM241 1411 The program should also create a dictionary containing course numbers and the names of the instructors that teach each course. The dictionary should have the following key-value pairs: Course...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT