python - 使用 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”在最后的返回行上。我该怎么办?
解决方案
您忘记了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)'
推荐阅读
- jenkins - 如何使每日 Jenkins 工作总结报告以表格格式发送到邮件
- microsoft-graph-api - Microsoft Graph - 添加带有异常的重复事件
- php - 如何在异步调用中读取传递给 php 的数组
- laravel - HostGator VPS 上的 Laravel 设置
- django - 用 django 计算两列之间的差异
- laravel - NextJS + Laravel + NGinx + Docker:无法在 getServerSideProps 中调用 API
- javascript - 创建继承自现有对象的新对象时 JavaScript 问题的三个点
- sorting - Camel 2.x 无法识别“preSort”文件组件参数
- python - 从基于 Django Channels 的脚本运行 Scrapy
- aspnetboilerplate - 如何根据 aspnetboilerplate 中的 AsyncCrudAppService 从自动生成的控制器路由中删除 GetAll/Get/Create/Delete/Update?