Question

In: Computer Science

from MyStack import MyStack def infixToPostfix(infixexpr):    prec = {}    prec["*"] = 3    prec["/"] = 3    prec["+"]...

from MyStack import MyStack

def infixToPostfix(infixexpr):

   prec = {}

   prec["*"] = 3

   prec["/"] = 3

   prec["+"] = 2

   prec["-"] = 2

   prec["("] = 1

   opStack = Stack()

   postfixList = []

   tokenList = infixexpr.split()

   for token in tokenList:

       if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":

           postfixList.append(token)

       elif token in prec:

       op_2=operand_stack.peek()

       operand_stack.pop()

       op_1=operand_stack.peek()

       operand_stack.pop()

       operand_stack.push("("+op_1+token+op_2+")")

   temporary_list.append(operand_stack.pop())

   for i in temporary_list[0]:

       infix_list.append(i)

   return " ".join(infix_list)

print(postfix_to_infix("3 6 7*+"))

def doMath(op, op1, op2):

  if op == "*":

      return op1 * op2

  elif op == "/":

      return op1 / op2

  elif op == "+":

      return op1 + op2

  else:

      return op1 - op2

def infixEval(expr):

   operandStack=MyStack()

   operatorStack=MyStack

   tokenList=expr.split()

   for token in tokenList:

       if token in "1234567890":

           operandStack.push(int(token))

       elif token in"*/+-":

           operatorStack.push(int(token))

       elif token== "(":

           continue

       elif token==")":

           operand2=operandStack.pop()

           operand1=operandStack.pop()

           operator=operatorStack.pop()

           result=doMath(operator,operand1, operand2)

           operandStack.push(result)

   return operandStack.pop()

print(infixEval("(3+(8*1))"))

Turn this direct infix evaluator from the above problem into a calculator.

Python

Solutions

Expert Solution

def calc():

  print("Select an operation.")

  print("1.Add , 2.Subtract , 3.Multiply , 4.Divide")

  while True:

      # Take input

    choice = input("Enter your choice of operation (1/2/3/4): ")

      # Check whether the choice is one of the defined options

    if (choice in ('1', '2', '3', '4')):

      num1 = float(input("Enter first number: "))

      num2 = float(input("Enter second number: "))

      num1 = str(num1)

      num2 = str(num2)

      if (choice == '1'):

        print(infixEval(num1+"+"+num2))

      elif choice == '2':

        print(infixEval(num1+"-"+num2))

        

      elif choice == '3':

        print(infixEval(num1+"*"+num2))

      elif choice == '4':

        print(infixEval(num1+"/"+num2))

      break

    else :

      print("Invalid Input")

calc()    


Related Solutions

import Stack def stack_mystery(myStack):      mystery=0     while not myStack.isEmpty():          value=myStack.pop()          if v
import Stack def stack_mystery(myStack):      mystery=0     while not myStack.isEmpty():          value=myStack.pop()          if value> mystery:              mystery=value                return mystery def main():    s=Stack.Stack()        s.push(20)        s.push(10)        s.push(50)        s.push(100)        s.push(40)        print(stack_mystery(s)) main() Answer the following questions a) What is the output of the print(stack_mystery(s)) statement in the main method? b) What is the task of the stack_mystery function? What does the mystery variable represent?
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def...
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def take_e(n, gen):     return [elem for (i, elem) in enumerate(gen) if i < n] def take_zc(n, gen):     return [elem for (i, elem) in zip(count(), gen) if i < n] FIBONACCI UNBOUNDED: def fibonacci_unbounded():     """     Unbounded Fibonacci numbers generator     """     (a, b) = (0, 1)     while True:         # return a         yield a         (a, b) = (b, a + b) SUPPOSED TO RUN THIS TO ASSIST WITH...
import random import turtle def isInScreen(win,turt): leftBound = -win.window_width() / 2 rightBound = win.window_width() / 2...
import random import turtle def isInScreen(win,turt): leftBound = -win.window_width() / 2 rightBound = win.window_width() / 2 topBound = win.window_height() / 2 bottomBound = -win.window_height() / 2 turtleX = turt.xcor() turtleY = turt.ycor() stillIn = True if turtleX > rightBound or turtleX < leftBound: stillIn = False if turtleY > topBound or turtleY < bottomBound: stillIn = False return stillIn def main(): wn = turtle.Screen() # Define your turtles here june = turtle.Turtle() june.shape('turtle') while isInScreen(wn,june): coin = random.randrange(0, 2) if...
from partition import partition def quicksort(a: list, l: int, u: int) -> None: '''Sort the given...
from partition import partition def quicksort(a: list, l: int, u: int) -> None: '''Sort the given list a in non-descending order. Precondition: 0 <= l and u < len(a)''' if l < u: mid = (l + u) // 2 three = [a[l], a[mid], a[u]] three.sort() if three[1] == a[l]: pivot_loc = l elif three[1] == a[u]: pivot_loc = u else: pivot_loc = mid a[u], a[pivot_loc] = a[pivot_loc], a[u] pivot = a[u] i = partition(a, l, u - 1, pivot)...
from typing import List def longest_chain(submatrix: List[int]) -> int: """ Given a list of integers, return...
from typing import List def longest_chain(submatrix: List[int]) -> int: """ Given a list of integers, return the length of the longest chain of 1's that start from the beginning. You MUST use a while loop for this! We will check. >>> longest_chain([1, 1, 0]) 2 >>> longest_chain([0, 1, 1]) 0 >>> longest_chain([1, 0, 1]) 1 """ i = 0 a = [] while i < len(submatrix) and submatrix[i] != 0: a.append(submatrix[i]) i += 1 return sum(a) def largest_rectangle_at_position(matrix: List[List[int]], x:...
from PIL import Image def stringToBits(string):     return str(bin(int.from_bytes(string.encode(), 'big')))[2:] def bitsToString(bits):     if bits[0:2] != '0b':         bits.
from PIL import Image def stringToBits(string):     return str(bin(int.from_bytes(string.encode(), 'big')))[2:] def bitsToString(bits):     if bits[0:2] != '0b':         bits = '0b' + bits     value = int(bits, 2)     return value.to_bytes((value.bit_length() + 7) // 8, 'big').decode() def writeMessageToRedChannel(file, message):     image = Image.open(file)     width, height = image.size     messageBits = stringToBits(message)     messageBitCounter = 0     y = 0     while y < height:         x = 0         while x < width:             r, g, b, a = image.getpixel((x, y))             print("writeMessageToRedChannel: Reading pixel %d, %d - Original values (%d, %d, %d, %d)"...
Please I seek assistance Python Programing import os import numpy as np def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path):...
Please I seek assistance Python Programing import os import numpy as np def generate_assignment_data(expected_grade_file_path, std_dev, output_file_path): """ Retrieve list of students and their expected grade from file, generate a sampled test grade for each student drawn from a Gaussian distribution defined by the student expected grade as mean, and the given standard deviation. If the sample is higher than 100, re-sample. If the sample is lower than 0 or 5 standard deviations below mean, re-sample Write the list of student...
#Python 3.7 "Has no attribute" error - def get():     import datetime     d = date_time_obj.date()...
#Python 3.7 "Has no attribute" error - def get():     import datetime     d = date_time_obj.date()     return(d) print(a["Date"]) print("3/14/2012".get()) How to write the "get" function (without any imput), to convery the format ""3/14/2012" to the format "2012-03-14", by simply using "3/14/2012".get() ?
import math import numpy as np import numpy.linalg from scipy.linalg import solve A = np.array([[-math.cos(math.pi/6),0, math.cos(math.pi/3),0,...
import math import numpy as np import numpy.linalg from scipy.linalg import solve A = np.array([[-math.cos(math.pi/6),0, math.cos(math.pi/3),0, 0, 0], [-math.sin(math.pi/6), 0, -math.sin(math.pi/3), 0, 0, 0], [math.cos(math.pi/6), 1, 0, 1, 0, 0], [math.sin(math.pi/6), 0, 0, 0, 1, 0], [0, -1, -math.cos(math.pi/3), 0, 0, 0], [0, 0, math.sin(math.pi/3), 0, 0, 1]]) b = np.array([0, 2000, 0, 0, 0, 0]) x = [0, 0, 0, 0, 0, 0] def seidel(a, x, b): # Finding length of a(3) n = len(a) # for loop for...
Convert from python 2 to 3 from Tkinter import * # the blueprint for a room...
Convert from python 2 to 3 from Tkinter import * # the blueprint for a room class Room(object): # the constructor def __init__(self,name,image): # rooms have a name, exits (e.g., south), exit locations (e.g., to the south is room n), # items (e.g., table), item descriptions (for each item), and grabbables (things that can # be taken and put into the inventory) self.name = name self.image = image self.exits = {} self.items = {} self.grabbables = [] # getters and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT