Question

In: Computer Science

I need to write an interpreter for arithmetic expressions in Python. This program receives an input...

I need to write an interpreter for arithmetic expressions in Python. This program receives an input string with an arithmetic expression and does:

1. prints a ">>>" as if it was a terminal

2. lets us allocate a variable to a a numeric value (as "a = 3") then it stores {'a':3} to a dictionary memory

3. whenever it receives an expression or input, transform it to postfix notation and print it (even when allocating variables)

4. it is able to operate with alerady allocated variables (so if i did put a = 2, then I can create expressions with A that will have a real value)

5. Stores and evaluates postfix notation expression in stacks

6. Is able to operate with the operands:

a. "(" ")" parethesis

b. unary + and unary -

c. exponentiation

d. multplication and division

e. binary sum and binary subtraction

when I type (__quit__) quits the program.

7. the program must be able to let me allocate variables to more than one digit strings (as 'yee') and operate with more than one digit numbers.

Solutions

Expert Solution

top = -1
array = []
output = []
precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
alpha_value = {}


def push(op):
    global top
    top += 1
    array.append(op)


def pop():
    global top
    if top != -1:
        top -= 1
        return array.pop()
    else:
        return "$"


def checkHigher(ch):
    result = False
    if ch in precedence and array[-1] in precedence:
        if precedence[ch] <= precedence[array[-1]]:
            result = True
    return result


while True:
    input_str = input(">>")
    if input_str == "(__quit__)":
        break
    if "=" in input_str:
        a_v = input_str.split("=")
        alpha_value[a_v[0]] = a_v[1]
    else:
        for ch in input_str:
            if ch.isalpha():
                output.append(ch)
            elif ch == "(":
                push(ch)
            elif ch == ")":
                while top != -1 and array[-1] != "(":
                    output.append(pop())
                if top != -1 and array[-1] != "(":
                    break
                else:
                    pop()
            else:
                while top != -1 and checkHigher(ch):
                    output.append(pop())
                push(ch)

        while top != -1:
            output.append(pop())

        last = []
        for i in output:
            if i in alpha_value:
                last.append(alpha_value[i])
            else:
                last.append(i)

        print("".join(last))

Related Solutions

I need to write a program in python for a restaurant. The program should let the...
I need to write a program in python for a restaurant. The program should let the user enter a meal number, then it should display the meal name, meal price, and meal calories. Also, needs the appropriate output if the user enters an invalid meal number. I am supposed to use a dictionary, but my problem is it keeps giving me an error and telling me my menu is not defined. Not sure what I am doing wrong. print ("Welcome...
Need this program in python. The data must be taken from user as input. Write a...
Need this program in python. The data must be taken from user as input. Write a program that prompts the user to select either Miles-to-Kilometers or Kilometers-to-Miles, then asks the user to enter the distance they wish to convert. The conversion formula is: Miles = Kilometers X 0.6214 Kilometers = Miles / 0.6214 Write two functions that each accept a distance as an argument, one that converts from Miles-to-Kilometers and another that converts from Kilometers-to-Miles The conversion MUST be done...
Write a program in Python to practice evaluating some logical expressions and determine whether the expressions...
Write a program in Python to practice evaluating some logical expressions and determine whether the expressions are equivalent. Read in a 0 or 1 integer value for each of the following variables: A, B, C, and D. Use an if…else statement to change the 0 and 1 integer values into True and False Boolean values. Booleans in Python have to have this capitalization (True/False, not true/false or TRUE/FALSE) and shouldn’t contain double quotes (which makes them a String instead of...
PYTHON Write a python program that encrypts and decrypts the user input. Note – Your input...
PYTHON Write a python program that encrypts and decrypts the user input. Note – Your input should be only lowercase characters with no spaces. Your program should have a secret distance given by the user that will be used for encryption/decryption. Each character of the user’s input should be offset by the distance value given by the user For Encryption Process: Take the string and reverse the string. Encrypt the reverse string with each character replaced with distance value (x)...
Write a program in python that corrects misspelled words. The input for the program is either...
Write a program in python that corrects misspelled words. The input for the program is either a string or a list of strings. The output should be a string or a list depending on the input and should have the spellings corrected. The speller should be able to correct at least the words listed below. You are free to use any data structures we have covered so far including lists and dictionaries. Your program should be in autocorrect.py. Here is...
IN PYTHON Write a program that takes in a positive integer as input, and outputs a...
IN PYTHON Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is: As long as x is greater than 0 Output x % 2 (remainder is either 0 or 1) x = x // 2 Note: The above algorithm outputs the 0's and 1's in reverse order. You will need to write a second function to reverse the string....
Python Program Write a program that will ask a user on how many input colored balls...
Python Program Write a program that will ask a user on how many input colored balls of the following codes: R-red, B-blue, W-white, G-green and O-orange -will he or she would like to enter in the program and print the total number of Red balls were encountered. Assume an uppercase and lower case letter will be accepted.
Write a program in python that takes a date as input and outputs the date's season....
Write a program in python that takes a date as input and outputs the date's season. The input is a string to represent the month and an int to represent the day. Ex: If the input is: April 11 the output is: Spring In addition, check if the string and int are valid (an actual month and day). Ex: If the input is: Blue 65 the output is: Invalid The dates for each season are: Spring: March 20 - June...
Python program. Write a function called cleanLowerWord that receives a string as a parameter and returns...
Python program. Write a function called cleanLowerWord that receives a string as a parameter and returns a new string that is a copy of the parameter where all the lowercase letters are kept as such, uppercase letters are converted to lowercase, and everything else is deleted. For example, the function call cleanLowerWord("Hello, User 15!") should return the string "hellouser". For this, you can start by copying the following functions discussed in class into your file: # Checks if ch is...
in python Using this baseline template, write a program to input a choice from a menu...
in python Using this baseline template, write a program to input a choice from a menu def calcArea(length, width):    pass    def CalcVolumeSa(length, width, height):    pass def menu():    pass        def getValuesArea(): pass    def getValuesVolSa(): pass       def main():    menu() if __name__ == "__main__":    main() [1] - Calculate Area of rectangle [2] - calculate Volume and Surface area of Rectangle [x} - Exit Please select Option: input the appropriate values and calculate...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT