类计算器程序中的 _validate(self, expr) 函数、_getPostfix(self) 函数和 value(self) 函数有问题

问题描述 投票:0回答:0

我必须使用提供的特定算法来编写此函数,以实现中缀到后缀表示法。我写的内容给我输出:setExpr error: Invalid Expression ''

我正在附上我目前所拥有的整个程序 . . .

不要修改这个类

类节点: def init(自我,数据): self.data = 数据
self.next = 无

def __str__(self):
    return "Node({})".format(self.data) 

__repr__ = __str__
                      

#===============================================部分我==============================================

类堆栈: """ >>> x = 堆栈() >>> x.isEmpty() 真的 >>> 长度(x) 0 >>> x.peek() >>> x.pop() >>> x 顶部:无 堆: >>> x.push(2) >>> x.isEmpty() 错误的 >>> 长度(x) 1个 >>> x.peek() 2个 >>> x.pop() 2个 >>> x 顶部:无 堆: >>> x.push(2) >>> x.push(4) >>> x.push(6) >>> x.isEmpty() 错误的 >>> 长度(x) 3个 >>> x 顶部:节点(6) 堆栈:6 <= 4 <= 2 >>> x.peek() 6个 >>> x.pop() 6个 “”“

# DO NOT modify this method
def __init__(self):
    self.top = None

# DO NOT modify this method
def __str__(self):
    temp=self.top
    out=[]
    while temp:
        out.append(str(temp.data))
        temp=temp.next
    out=' <= '.join(out)
    return ('Top: {}\nStack: {}'.format(self.top,out))

# DO NOT modify this method
__repr__=__str__




def isEmpty(self):
    # Checks to see if the stack is empty by checking the top of the stack
    if self.top == None:
        return True
    else:
        return False

def __len__(self): 
    # Determines the length of the stack with a loop and counter until it runs out of elements
    length = self.top
    counter = 0
    while length != None:
        counter += 1
        length = length.next
    return counter

def push(self, data):
    if self.top == None:
        self.top = Node(data)
    else:
        newNode = Node(data)
        newNode.next = self.top
        self.top = newNode

        
 
def pop(self):
    if self.isEmpty():
        return None
    else:
        if self.top is not None:
            self.top == self.top.next
        return self.top.data

    
def peek(self):
    # Returns the data in the top node of the stack
    if self.isEmpty():
        return None
    else:
        return self.top.data
    

#===============================================部分二==============================================

班级计算器:

# DO NOT modify this member
priority = { '+':1, '-':1, '*':2, '/':2, '^':3 }

# DO NOT modify this method
def __init__(self):
    self.__expr = None

    
# DO NOT modify this method
@property
def expr(self):
    return self.__expr


# DO NOT modify this method
@expr.setter
def expr(self, new_expr):
    if isinstance(new_expr, str) and self._validate(new_expr):
        self.__expr=new_expr
    else:
        print('setExpr error: Invalid expression')
        return None


    


    
def _isNumber(self, token):
    """
    >>> x=Calculator()
    >>> x._isNumber('5')
    True
    >>> x._isNumber('+5')
    True
    >>> x._isNumber('-5')
    True
    >>> x._isNumber('5.')
    True
    >>> x._isNumber('-5.')
    True
    >>> x._isNumber('+5.')
    True
    >>> x._isNumber('0.5')
    True
    >>> x._isNumber('-0.5')
    True
    >>> x._isNumber('.5')
    True
    >>> x._isNumber('-.5')
    True
    >>> x._isNumber(' 4.560 ')
    True
    >>> x._isNumber('4 56')
    False
    >>> x._isNumber('4.56a')
    False
    >>> x._isNumber('-4.56a')
    False
    >>> x._isNumber('4.5a6')
    False
    """
    # returns True if token is a string and is able to convert to a float
    try:
        float(token)
        return True
    except:
        return False
    pass



    
def _validate(self, expr):
    """
    >>> x=Calculator(); x._validate('2 ^ 4')
    True
    >>> x=Calculator(); x._validate('2')
    True
    >>> x=Calculator(); x._validate('2.1 * 5 + 3 ^ 2 + 1 + 4.45')
    True
    >>> x=Calculator(); x._validate('2 * 5.34 + 3 ^ 2 + 1 + 4')
    True
    >>> x=Calculator(); x._validate('2.1 * 5 + 3 ^ 2 + 1 + 4')
    True
    >>> x=Calculator(); x._validate('( 2.5 )')
    True
    >>> x=Calculator(); x._validate ('( ( 2 ) )')
    True
    >>> x=Calculator(); x._validate ('2 * ( ( 5 + -3 ) ^ 2 + ( 1 + 4 ) )')
    True
    >>> x=Calculator(); x._validate ('( 2 * ( ( 5 + 3 ) ^ 2 + ( 1 + 4 ) ) )')
    True
    >>> x=Calculator(); x._validate ('( ( 2 * ( ( 5 + 3 ) ^ 2 + ( 1 + 4 ) ) ) )')
    True
    >>> x=Calculator(); x._validate('2 * ( -5 + 3 ) ^ 2 + ( 1 + 4 )')
    True
    >>> x = Calculator(); x._validate('2 * 5 + 3 ^ + -2 + 1 + 4')
    False
    >>> x = Calculator(); x._validate('2 * 5 + 3 ^ - 2 + 1 + 4')
    False
    >>> x = Calculator(); x._validate('2    5')
    False
    >>> x = Calculator(); x._validate('25 +')
    False
    """
    ## YOUR CODE STARTS HERE
    
    pass
    
                    
    



# self.__expr must be a valid expression
# validity of self.__expr is checked when calling the property method @expr.setter
# - see @expr.setter for detail

def _getPostfix(self):
    """
    Required: _getPostfix must create and use a Stack for expression processing
    >>> x=Calculator()
    >>> x.expr = '2 ^ 4'; x._getPostfix()
    '2.0 4.0 ^'
    >>> x.expr = '2'; x._getPostfix()
    '2.0'
    >>> x.expr = '2.1 * 5 + 3 ^ 2 + 1 + 4.45'; x._getPostfix()
    '2.1 5.0 * 3.0 2.0 ^ + 1.0 + 4.45 +'
    >>> x.expr ='2 * 5.34 + 3 ^ 2 + 1 + 4'; x._getPostfix()
    '2.0 5.34 * 3.0 2.0 ^ + 1.0 + 4.0 +'
    >>> x.expr = '2.1 * 5 + 3 ^ 2 + 1 + 4'; x._getPostfix()
    '2.1 5.0 * 3.0 2.0 ^ + 1.0 + 4.0 +'
    >>> x.expr = '( 2.5 )'; x._getPostfix()
    '2.5'
    >>> x.expr = '( ( 2 ) )'; x._getPostfix()
    '2.0'
    >>> x.expr = '2 * ( ( 5 + -3 ) ^ 2 + ( 1 + 4 ) )'; x._getPostfix()
    '2.0 5.0 -3.0 + 2.0 ^ 1.0 4.0 + + *'
    >>> x.expr = '( 2 * ( ( 5 + 3 ) ^ 2 + ( 1 + 4 ) ) )'; x._getPostfix()
    '2.0 5.0 3.0 + 2.0 ^ 1.0 4.0 + + *'
    >>> x.expr = '( ( 2 * ( ( 5 + 3 ) ^ 2 + ( 1 + 4 ) ) ) )'; x._getPostfix()
    '2.0 5.0 3.0 + 2.0 ^ 1.0 4.0 + + *'
    """

    # convert an expression from infix to postfix
    ratorStack = Stack()  # must use ratorStack to get a postfix expression of self.__expr 

    array = []
    
    for token in array:
        if self._isNumber(token):
            self.__expr()
            array.append(float(token))
        elif token == '(':
            ratorStack.push(token)
        elif token == ')':
            while self.top != '(':
                ratorStack.pop(token)
                array.append(token)
            else:
                ratorStack.pop(token)
                break
                
        elif token is self.priority:
            while ratorStack != None:
                if self.top != '(' and self.priority(self.top) >= self.priority(token):
                    ratorStack.pop(token)
                    array.append(token)
            else:
                ratorStack.push(token)
                break
        elif token is self.priority:
            while ratorStack != None:
                if self.top != '(' and self.priority(self.top) > self.priority(token):
                    ratorStack.pop(token)
                    array.append(token)
            else:
                ratorStack.push(token)
        else:
            return None
        
    while not ratorStack.isEmpty():
        ratorStack.pop(token)
        array.append(token)

    return ' '.join(array)

    
    



# This property method must
# 1. converts self.__expr to a postfix expression by calling self._getPostfix
# 2. use a stack to compute the final result of the postfix expression
@property
def value(self):
    '''
    >>> x=Calculator()
    >>> x.expr = '4 + 3 - 2'; x.value
    5.0
    >>> x.expr = '-2 + 3.5'; x.value
    1.5
    >>> x.expr = '4 + 3.65 - 2 / 2'; x.value
    6.65
    >>> x.expr = '23 / 12 - 223 + 5.25 * 4 * 3423'; x.value
    71661.91666666667
    >>> x.expr = ' 2 - 3 * 4'; x.value
    -10.0
    >>> x.expr = '7 ^ 2 ^ 3'; x.value
    5764801.0
    >>> x.expr = ' 3 * ( ( ( 10 - 2 * 3 ) ) )'; x.value
    12.0
    >>> x.expr = '8 / 4 * ( 3 - 2.45 * ( 4 - 2 ^ 3 ) ) + 3'; x.value
    28.6
    >>> x.expr = '2 * ( 4 + 2 * ( 5 - 3 ^ 2 ) + 1 ) + 4'; x.value
    -2.0
    >>> x.expr = ' 2.5 + 3 * ( 2 + ( 3.0 ) * ( 5 ^ 2 - 2 * 3 ^ ( 2 ) ) * ( 4 ) ) * ( 2 / 8 + 2 * ( 3 - 1 / 3 ) ) - 2 / 3 ^ 2'; x.value
    1442.7777777777778
    '''

    if not isinstance(self.__expr, str) or len(self.__expr)<=0:
        print("Argument error in calculate")
        return None

    calcStack = Stack()   # must use calcStack to compute the expression
    
    pass

if name == 'main': 导入doctest

## Uncomment this line if you want to run doctest by function.
## Replace get_words with the name of the function you want to run
#doctest.run_docstring_examples(Calculator._validate, globals(), verbose=True, name='hw5')

## Uncomment this line if you want to run the docstring
## in all functions
doctest.testmod()











    

This is the algorithm for infix to postfix that needs to be used for getPostfix. I tried my best with implementing, but I keep getting an error

python algorithm class postfix-notation infix-notation
© www.soinside.com 2019 - 2024. All rights reserved.