python - 在 Python 中使用递归遇到问题的初学者
问题描述
练习是创建一个接受另一个函数和一个参数的递归函数。我遇到了一个语义错误,我的函数没有做我希望它做的事情。我是初学者,所以这可能是一个非常容易解决的问题,但我似乎找不到它。感谢您提供任何帮助:
def do_this(func, arg): # this function will call another function (func) a maximum of (arg) times
arg -= 1 # in order to ensure that we call (func) only (arg) times, I reduce (arg) by 1
#to start
if arg <= 0:
return
else:
do_this(func, arg) # here is where the recursion takes place when this function calls itself - if
# this is written correctly, then this function will call itself (arg) times
def print_n(s, n): # this function is also recursive, it will print the arguments passed to it
#from the function 'do_this'
if n <= 0: # each time it completes a cycle of 'n' iterations it will print the bundle
#number
x = 1
print("Bundle Number", x)
x += 1
return
else:
print(s)
print_n(s, n - 1)
do_this(print_n("hello", 2), 4)
这应该打印以下内容:
hello
hello
Bundle Number 1
hello
hello
Bundle Number 2
hello
hello
Bundle Number 3
hello
hello
Bundle Number 4
解决方案
do_this
调用自身,但从未真正调用func
.
此外,在将参数传递给print_n
之前,您不应该将参数传递给do_this
- 您应该将函数本身以及执行调用所需的所有数据一起传递。传递参数将导致调用print_n
被实际执行。通常,print_n
然后将返回值传递给do_this
,但没有返回值。
请记住,您希望将print_n
自身传递给do_this
,而不仅仅是print_n
.
推荐阅读
- c++ - 如何找到第二小的向量?
- c# - Xaml UI Designer 对于 .net core 3.0 中的 wpf 项目不活动
- javascript - Cookie 在同意之前设置
- microsoft-graph-api - 图表 - 是否有更简单/更快的方法来删除 SharePoint 列表中的所有项目?
- video - 使用 FFmpeg 创建单个视频表单 3 个单独的视频
- java - YAML 文件:读取 Yaml 文件并以相同格式写入文件
- swift - 了解闭包的目的
- httpclient - 在 Apache HttpClient 中,我如何知道 2 个请求是否使用相同的连接?
- sql - PostgreSQL 错误:返回集合的函数必须出现在 FROM 的顶层
- c# - 如何在棱镜 IContainerRegistry 中为 2 个接口注册相同的实例(= 单例)