Question

CMPT 145 UNIVERSITY OF SASKATCHEWAN Department of Computer Scienes 176 Thoaldo Bin 10Sceace Pace, Saskn SK, 57N 5Ca, Cra alepСМРТ 145 UNIVERSITY OF SASKATCHEWAN Department of Computer Sciences 176 Thaduldeg 10Scieace Place, Sukoon, SK, 5TN SC, Craa a

**TStack.py below**

# CMPT 145: Linear ADTs
# Defines the Stack ADT
#
# A stack (also called a pushdown or LIFO stack) is a compound 
# data structure in which the data values are ordered according 
# to the LIFO (last-in first-out) protocol.
#
# Implementation:
# This implementation was designed to point out when ADT operations are
# used incorrectly.


def create():
    """
    Purpose
        creates an empty stack
    Return
        an empty stack
    """
    return '__Stack__',list()


def is_empty(stack):
    """
    Purpose
        checks if the given stack has no data in it
    Pre-conditions:
        stack is a stack created by create()
    Return:
        True if the stack has no data, or false otherwise
    """
    if type(stack) is tuple:
        t,s = stack
        assert t == '__Stack__', 'Type Error : Expected __Stack__ but received '+t
        return len(s) == 0
    else:
        assert False, 'Type Error: Expected __Stack__ but received '+str(type(stack))



def size(stack):
    """
    Purpose
        returns the number of data values in the given stack
    Pre-conditions:
        stack: a stack created by create()
    Return:
        The number of data values in the queue
    """
    if type(stack) is tuple:
        t,s = stack
        assert t == '__Stack__', 'Type Error: Expected __Stack__ but received '+t
        return len(s)
    else:
        assert False, 'Type Error: Expected __Stack__ but received '+str(type(stack))


def push(stack, value):
    """
    Purpose
        adds the given data value to the given stack
    Pre-conditions:
        queue: a stack created by create()
        value: data to be added
    Post-condition:
        the value is added to the stack
    Return:
        (none)
    """
    if type(stack) is tuple:
        t,s = stack
        assert t == '__Stack__', 'Type Error: Expected __Stack__ but received '+t
        s.append(value)
    else:
        assert False, 'Type Error: Expected __Stack__ but received '+str(type(stack))


def pop(stack):
    """
    Purpose
        removes and returns a data value from the given stack
    Pre-conditions:
        stack: a stack created by create()
    Post-condition:
        the top value is removed from the stack
    Return:
        returns the value at the top of the stack
    """
    if type(stack) is tuple:
        t,s = stack
        assert t == '__Stack__', 'Type Error: Expected __Stack__ but received '+t
        return s.pop()
    else:
        assert False, 'Type Error: Expected __Stack__ but received '+str(type(stack))

def peek(stack):
    """
    Purpose
        returns the value from the front of given stack without removing it
    Pre-conditions:
        stack: a stack created by create()
    Post-condition:
        None
    Return:
        the value at the front of the stack
    """
    if type(stack) is tuple:
        t,s = stack
        assert t == '__Stack__', 'Type Error: Expected __Stack__ but received '+t
        return s[-1]
    else:
        assert False, 'Type Error: Expected __Stack__ but received '+str(type(stack))
CMPT 145 UNIVERSITY OF SASKATCHEWAN Department of Computer Scienes 176 Thoaldo Bin 10Sceace Pace, Saskn SK, 57N 5Ca, Cra alephi -486, Facinle 0) -44 Summer-Spring 2019 Principles of Compater Science Question 2 (20 points): Purpose: To work with a real application for stacks and be more familiar to work with an ADT that was not developed by you Degree of Difficulty: Moderate In class, we saw how to evaluate numerical expressions expressed in post-fix (also known as reverse Polish notation). The code for that is available on the course Moodle. It turns out to be fairly easy to write a similar program to evaluate expressions using normal mathematical notation. Input The input will be a mathematical expression in the form of a string, using at least the four arithmetic opera- tors ,x, /as well as pairs of brackets. To avoid problems that are not of interest to our work right now. we'll also use lots of space where we normally wouldn't. We'll use spaces between operators, numbers and brackets. Here's a list of expressions for example example1 '( 1 1 )' should evaluate to 2 = '(( 11 + 12 * 13 should evaluate to 299 example2 Notice particularly that we are using brackets explicitly for every operator. In every-day math, brackets are sometimes left out, but in this is not an option here. Every operation must be bracketed! The brackets and the spacing eliminate programming problems that are not of interest to us right now. Hint: You will find it useful to split the string into sub-strings using split, and even to put all the substrings in a Queue, as we did for the PostFix program. Algorithm We will use two stacks: one for numeric values, as in the PostFix program, and a second stack just for the operators. We take each symbol from the input one at a time, and then decide what to do with it If the symbol is '(0, ignore it. If the symbol is a string that represents a numeric value (use the function isfloat (). provided in the script isfloat.py), convert to a floating point value and push it on the numeric value stack If the symbol is an operator, push the operator on the operator stack. If the symbol is ')'. pop the operator stack, and two values from the numeric value stack, do the appropriate computation, and push the result back on the numeric value stack. You should write a function to do all this processing. Since the objective here is to practice using stacks, you must use the Stack ADT provided for this assign- ment. Also, you may assume that the input will be syntactically correct, for full marks. For this question your program does not need to be robust against syntactically incorrect expressions. Using the Stack ADT Download the Stack ADT implementation named TStack.py from the Assignment 4 page on Moodle. To help you avoid errors, this implementation of the Stack ADT does not allow you to violate the ADT in a careless way. You do not need to understand the code in the file TStack.py. You do not even need to look at it. We will study simpler and more accessible implementations later in the course. You should focus on using the Stack ADT operations correctly. TStack.py has the same Stack ADT interface, and has been thoroughly tested. If your script does not use the Stack ADT correctly, or if you violate the ADT Principle. runtime error will be caused. a Page 6
СМРТ 145 UNIVERSITY OF SASKATCHEWAN Department of Computer Sciences 176 Thaduldeg 10Scieace Place, Sukoon, SK, 5TN SC, Craa alapha 64 Fac 00)-404 Summer-Spring 2019 Principles of Computer Science Testing This is the first script whose testing needs to be very diligent, and will end up being extensive. Write a test script that checks each arithmetic operation in very simple cases (one operator each), and then a number of more complicated cases using more complicated expressions. Your test script should do unit testing C of your function to evaluate expressions. You can add tests of any other functions you write, but focus on testing the expressions What to Hand In Your function, written in Python, in a file named a4q2.py Your test-script for the function, in a file called a4q2_test.py Be sure to include your name, NSID, student number, course number and laboratory section at the top of all documents. Evaluation 10 marks: Your evaluation function correctly evaluates expressions of the form given above. It uses two Stacks, both are created by the TStack ADT 2 marks: The evaluation function correctly handles numeric data by pushing onto a numbers stack 2 marks. The evaluation function correctly handles operators by pushing on an operator stack 4 marks. The evaluation function correctly evaluates expressions when a ') is encountered. Two values are popped from the numbers stack and an operator is popped from the operator stack. The correct operation is performed, and the result is pushed back on the numbers stack - 2 marks. When there is nothing left to evaluate, the result is popped from the numbers stack. 10 marks: Your test script covers all the operations individually once, and in combination. - 2 mark each: Every operator is tested. - 2 marks Testing includes at least one expression with several nested operations.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

NOTE: Since you have not provided isfloat() function, I have used my own isfloat() which is compatible with the code.

CODE:

# CMPT 145: Linear ADTs
# Defines the Stack ADT
#
# A stack (also called a pushdown or LIFO stack) is a compound 
# data structure in which the data values are ordered according 
# to the LIFO (last-in first-out) protocol.
#
# Implementation:
# This implementation was designed to point out when ADT operations are
# used incorrectly.


def create():
    """
    Purpose
        creates an empty stack
    Return
        an empty stack
    """
    return '__Stack__',list()


def is_empty(stack):
    """
    Purpose
        checks if the given stack has no data in it
    Pre-conditions:
        stack is a stack created by create()
    Return:
        True if the stack has no data, or false otherwise
    """
    if type(stack) is tuple:
        t,s = stack
        assert t == '__Stack__', 'Type Error : Expected __Stack__ but received '+t
        return len(s) == 0
    else:
        assert False, 'Type Error: Expected __Stack__ but received '+str(type(stack))



def size(stack):
    """
    Purpose
        returns the number of data values in the given stack
    Pre-conditions:
        stack: a stack created by create()
    Return:
        The number of data values in the queue
    """
    if type(stack) is tuple:
        t,s = stack
        assert t == '__Stack__', 'Type Error: Expected __Stack__ but received '+t
        return len(s)
    else:
        assert False, 'Type Error: Expected __Stack__ but received '+str(type(stack))


def push(stack, value):
    """
    Purpose
        adds the given data value to the given stack
    Pre-conditions:
        queue: a stack created by create()
        value: data to be added
    Post-condition:
        the value is added to the stack
    Return:
        (none)
    """
    if type(stack) is tuple:
        t,s = stack
        assert t == '__Stack__', 'Type Error: Expected __Stack__ but received '+t
        s.append(value)
    else:
        assert False, 'Type Error: Expected __Stack__ but received '+str(type(stack))


def pop(stack):
    """
    Purpose
        removes and returns a data value from the given stack
    Pre-conditions:
        stack: a stack created by create()
    Post-condition:
        the top value is removed from the stack
    Return:
        returns the value at the top of the stack
    """
    if type(stack) is tuple:
        t,s = stack
        assert t == '__Stack__', 'Type Error: Expected __Stack__ but received '+t
        return s.pop()
    else:
        assert False, 'Type Error: Expected __Stack__ but received '+str(type(stack))

def peek(stack):
    """
    Purpose
        returns the value from the front of given stack without removing it
    Pre-conditions:
        stack: a stack created by create()
    Post-condition:
        None
    Return:
        the value at the front of the stack
    """
    if type(stack) is tuple:
        t,s = stack
        assert t == '__Stack__', 'Type Error: Expected __Stack__ but received '+t
        return s[-1]
    else:
        assert False, 'Type Error: Expected __Stack__ but received '+str(type(stack))
        
        
def isfloat(val):
    try:
        v = float(val)
        return True
    except:
        return False
        
        
def evaluate(exp):
    # Create empty stacks
    value_stack = create()
    operator_stack = create()
    
    lst = exp.split() # Making list of characters in the expression
    
    for char in lst:
        
        if isfloat(char):
            val = float(char)
            push(value_stack,val)
            
        elif char == '+' or char == '-' or char == '*' or char == '/':
            push(operator_stack,char)
            
        elif char  == ')':
            val1 = pop(value_stack)
            val2 = pop(value_stack)
            operator = pop(operator_stack)
            
            if operator == '+':
                result = val1+val2
            elif operator == '-':
                val1,val2 = val2,val1
                result = val1-val2
            elif operator == '*':
                result = val1*val2
            elif operator == '/':
                val1,val2 = val2,val1
                result = val1/val2
            else:
                print("Unknown operator")
                break
                
            push(value_stack,result)
            
        else:
            pass
    
    return(pop(value_stack))        
    
def test():
    print("--------TESTING INDIVIDUAL OPERATORS----------")
    print('"( 4 + 5 )" =',evaluate("( 4 + 5 )"))
    print('"( 4 - 5 )" =',evaluate("( 4 - 5 )"))
    print('"( 4 * 5 )" =',evaluate("( 4 * 5 )"))
    print('"( 4 / 5 )" =',evaluate("( 4 / 5 )"))
    assert evaluate("( 4 + 5 )") == 9
    assert evaluate("( 4 - 5 )") == -1
    assert evaluate("( 4 * 5 )") == 20
    assert evaluate("( 4 / 5 )") == 0.8
    print("--------OPERATORS WORK CORRECTLY----------")
    print()
    print("--------TESTING EXPRESSIONS------------")
    print('"( ( 11 / 12 ) * 13 ) " = ',evaluate("( ( 11 / 12 ) * 13 ) "))
    print('"( ( 11 + 12 ) - 13 ) " = ',evaluate("( ( 11 + 12 ) - 13 ) "))
    print('"( ( 11 + 12 ) * 13 ) " = ',evaluate("( ( 11 + 12 ) * 13 ) "))
    
    assert evaluate("( ( 11 / 12 ) * 13 ) ") == 11.916666666666666
    assert evaluate("( ( 11 + 12 ) - 13 ) ") == 10.0
    assert evaluate("( ( 11 + 12 ) * 13 ) ") == 299.0
    print("--------EXPRESSIONS WORK CORRECTLY---------")
    
    
      
test()

OUTPUT:

def evaluate(exp) # Create empty stacks value_stack operator_stack create() create() exp.split) # 1st Making List of characte

def test) print ( print( print(4 print(4* 5 ) =,evaluate(( 4 * 5 ))) print(4 5 ) =,evaluate(( 4 / 5 ))) assert

Add a comment
Know the answer?
Add Answer to:
**TStack.py below** # CMPT 145: Linear ADTs # Defines the Stack ADT # # A stack (also called a pushdown or LIFO stack)...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In c++ Section 1. Stack ADT – Overview  Data Items The data items in a stack...

    In c++ Section 1. Stack ADT – Overview  Data Items The data items in a stack are of generic DataType. This means use should use templating and your Node class. Structure  The stack data items are linearly ordered from the most recently added (the top) to the least recently added (the bottom). This is a LIFO scheme. Data items are inserted onto (pushed) and removed from (popped) the top of the stack.  Operations  Constructor. Creates an empty stack.  Copy constructor....

  • By using PYTHON language Postfix to Infix using Stack Develop a stack application that can convert...

    By using PYTHON language Postfix to Infix using Stack Develop a stack application that can convert Postfix notation to Infix notation using the following algorithm. In your stack application, you can use only two stacks, one for a stack that can store Postfix notation, and the other is a stack to store infix notation. Also, it would help if you had a function to distinguish between an operation or an operand. Input A B C * + D E /...

  • Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns...

    Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are...

    We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are written in-between the operands). In a computer’s language, however, it is preferred to have the operators on the right side of the operands, i.e. 5 2 +. For more complex expressions that include parenthesis and multiple operators, a compiler has to convert the expression into postfix first and then evaluate the resulting postfix. Write a program that takes an “infix” expression as input, uses...

  • Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The...

    Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The application will be to add large numbers. Review adding large numbers Remember that we can use stacks to safely add integer values that overflow the int data type g. in Java, the maximum possible int value Integer.MAX_VALUE is: 2147483647 so any int addition larger than this will overflow and fail Using stacks to add large numbers safely Will actually represent the large integers to...

  • Stacks are used by compilers to help in the process of evaluating expressions and generating machine...

    Stacks are used by compilers to help in the process of evaluating expressions and generating machine language code.In this exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like 3 + 4and 7 / 9in which the operator (+ or / here) is written between its operands—this is called infix notation. Computers “prefer” postfix notation in which the operator is written to the right of its two operands. The preceding...

  • EVALUATING GENERAL INFIX EXPRESSIONS INTRODUCTION The notation in which we usually write arithmetic expressions is called infix notation;...

    EVALUATING GENERAL INFIX EXPRESSIONS INTRODUCTION The notation in which we usually write arithmetic expressions is called infix notation; in it, operators are written between their operands: X + Y. Such expressions can be ambiguous; do we add or multiply first in the expression 5 + 3 * 2? Parentheses and rules of precedence and association clarify such ambiguities: multiplication and division take precedence over addition and subtraction, and operators associate from left to right. This project implements and exercises a stack-based algorithm that evaluates...

  • Total point: 15 Introduction: For this assignment you have to write a c program that will...

    Total point: 15 Introduction: For this assignment you have to write a c program that will take an infix expression as input and display the postfix expression of the input. After converting the postfix expression, the program should evaluate the expression from the postfix and display the result. What should you submit? Write all the code in a single file and upload the .c file. Problem We as humans write math expression in infix notation, e.g. 5 + 2 (the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT