首页 > 解决方案 > 在 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

标签: pythonfunctionrecursion

解决方案


do_this调用自身,但从未真正调用func.

此外,在将参数传递给print_n之前,您不应该将参数传递给do_this- 您应该将函数本身以及执行调用所需的所有数据一起传递。传递参数将导致调用print_n被实际执行。通常,print_n然后将返回值传递给do_this,但没有返回值。

请记住,您希望将print_n自身传递给do_this,而不仅仅是print_n.


推荐阅读