首页 > 解决方案 > 使用 Python 中的递归进行 TypeError 的赋值

问题描述

我正在编写一组代码,我必须将循环转换为递归函数,而教授无法提供帮助,也无法联系到我的朋友。循环函数是这样的:

 def __str__(self):
     """ Returns a string representation of the list with a space between each item.
         Precondition:  none
         Postcondition:  Returns a string representation of the list with a space between each item.
     """
     resultStr = "(head)"
     current = self._head
     while current != None:
         resultStr += " " + str(current.getData())
         current = current.getNext()
     return resultStr + " (tail)"

到目前为止我输入的递归函数是这样的:

def __str__(self):
        """ Returns a string representation of the list with a space between each item.
            Precondition:  none
            Postcondition:  Returns a string representation of the list with a space between each item.
        """
        
        def strHelper(current):
            if current != None:
                str(current.getData()) + " " + strHelper(current.getNext())
            else:
                return ""
        
        # Start of __str__ method execution by passing pointer to first node in list
        return "(head) " + strHelper(self._head) + "(tail)"

教授基本上说:“这应该行得通!” 但我仍然得到一个 TypeError 读取“只能将 str(不是“NoneType”)连接到 str”在最后的返回行上。我该怎么办?

标签: pythonrecursiontypeerror

解决方案


您忘记了return辅助函数中的关键字。

def __str__(self):
        
    def strHelper(current):
        if current is not None:
            return str(current.getData()) + " " + strHelper(current.getNext())
        else:
            return ""
        
    return "(head) " + strHelper(self._head) + "(tail)"

不过,我会考虑用迭代替换递归。

def __str__(self):

    def strHelper(current):
        while current is not None:
            yield str(current.getData())
            current = current.getNext()

    return f'(head) {" ".join(strHelper(self._head))} (tail)'

您的字符串助手还构成了更通用迭代器的基础:

def __iter__(self):
    current = self._head
    while current is not None:
        yield current
        current = current.getNext()

def __str__(self):
    return f'(head) {" ".join(str(x.getData()) for x in self)} (tail)'

推荐阅读