Question

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 :)

Homework Answers

Answer #1

Here is the python code to given question.

Sample outputs are added at the end.

Code:

#create stack class
class stack:
    
    
    #initialize stack
    def __init__(self):
        
        self.stackList=[]
        self.top=-1
    
    
    #pushes value into stack
    def push(self,value):
        
        self.stackList.append(value)   #appends value into stack
        self.top+=1       #increments top by 1
    
    
    #pops the element at top of stack
    def pop(self):
        
        if self.top!=-1:        #checks if stack is not empty
            
            self.top-=1        #decrements the value of top by 1
            return self.stackList.pop()     #returns the top element of stack
          
          
          
#function to evaluate postfix expression  
def evaluatePostfix(expression):
    
    expressionList=expression.split(' ')     #converts string words to list
    
    stackObject=stack()      #creates a new stack object
    
    for i in expressionList:
        
        if i.isdigit():       #checks if i is a number
            
            stackObject.push(int(i))      #pushes the number into top of stack
        
        else:
            
            value1=stackObject.pop()      #pops element at top of stack
            
            value2=stackObject.pop()      #pops element at top of stack
            
            if i=='+':
                
                stackObject.push(int(value2+value1))     #pushes value2+value1 into the stack
            
            elif i=='-':
    
                stackObject.push(int(value2-value1))        #pushes value2-value1 into the stack
            
            elif i=='*': 
                
                stackObject.push(int(value2*value1))       #pushes value2*value1 into the stack
            
            elif i=='/':
                
                 stackObject.push(int(value2/value1))      #pushes value2/value1 into the stack
            
            elif i=='^':
                
                stackObject.push(int(value2**value1))    #pushes value2**value1 into the stack
            
    return stackObject.pop()    #returns top element of stack


def main():
    
    inputExpression=input("Enter postfix expression: ")    #takes input expression from user
    
    print(evaluatePostfix(inputExpression))     #calls evaluatePostfix method and prints the value returned
    
if __name__=="__main__":
    
    main()    #calls main
    
    
      

Sample output-1:

Sample output-2:

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
write a function call character_thing (string, character) that takes in a string and a character. The...
write a function call character_thing (string, character) that takes in a string and a character. The function will return the number of times the character appears in the string. please be in python
Write a function named "replacement" that takes a string as a parameter and returns an identical...
Write a function named "replacement" that takes a string as a parameter and returns an identical string except with every instance of the character "i" replaced with the character "n python
Q1) Write a Python function partial_print, which takes one parameter, a string, and prints the first,...
Q1) Write a Python function partial_print, which takes one parameter, a string, and prints the first, third, fifth (and so on) characters of the strings, with each character both preceded and followed by the ^ symbol, and with a newline appearing after the last ^ symbol. The function returns no value; its goal is to print its output, but not to return it. Q2) Write a Python function called lines_of_code that takes a Path object as a parameter, which is...
C++ Using the Stack operations, write a pseudocode routine, dupA, that takes aStack for string, checks...
C++ Using the Stack operations, write a pseudocode routine, dupA, that takes aStack for string, checks to see if the top starts with ‘A’ or ‘a’. If so, duplicate the top of the stack (i.e. pop a copy of that value onto the stack) else if length > 10, pop it off the stack
Write a Python function that takes a filename as a parameter and returns the string 'rows'...
Write a Python function that takes a filename as a parameter and returns the string 'rows' if a file was written row by row, and 'columns' if the file was written column by column. You would call the function with a command like filetype = myfunc(filename).
Java Please [(1)] A palindrome is a string that reads the same forwards as backwards. Using...
Java Please [(1)] A palindrome is a string that reads the same forwards as backwards. Using only a fixed number of stacks and queues, the stack and queue ADT functions, and a fixed number of int and char variables, write an algorithm to determine if a string is a palindrome. Assume that the string is read from standard input one character at a time. The algorithm should output true or false as appropriate [(2)] Let Q be a non-empty queue,...
1.Write a function which takes a string that contains two words separated by any amount of...
1.Write a function which takes a string that contains two words separated by any amount of whitespace, and returns a string in which the words are swapped around and the whitespace is preserved. Hint: use regular expressions where \s detects the whitespaces in a string. Example: given "Hello     World", return "World         Hello" 2.Pandas exercises: Write a python program using Pandas to create and display a one-dimensional array-like object containing an array of data. Write a python program using Pandas to...
4. Create a function, which takes as input a string and a letter. Determine whether or...
4. Create a function, which takes as input a string and a letter. Determine whether or not the letter is present in the string. The function should return a logical true/false if the given letter is present/absent. HINT: use find and isempty. Please anyone helping me with this question can you code using Matlab software, please.
python pls Create function math_life() this function takes one or more argument. If this function called...
python pls Create function math_life() this function takes one or more argument. If this function called with no argument, raise typeError. The math_life() function returns to a function defined inside. this will take a one argument. For the second argument, it will calculate second function passed to math_life(). You should assume that the math_life() passed x functions, when it called the x times it will calculate the xth function passed to math_life() arguments when it called x+1 time it again...
Implement function reverse that takes a 2D list (a list of list of integers) and returns...
Implement function reverse that takes a 2D list (a list of list of integers) and returns a new 2D list where the items in each row are in reverse order. You maynot use slicing. You may not modify the input list. The returned list should be completely new in memory – no aliases with the input 2D list. From list methods, you may use only the .append(). Examples: reverse([[1,2,3],[4,5,6]])       ->    [[3,2,1],[6,5,4]] reverse([[1,2],[3,4],[5,6]])     ->    [[2,1],[4,3][6,5]] True False In python please
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT