首页 > 解决方案 > 多重递归内的计数器

问题描述

所以我正在编写一个具有多个递归函数调用的代码。而且我想在满足某些条件时增加一个计数器。


def funct(n):
   return rec_func(a,b)

def rec_func(x,y):
    global counter
    if <conditiona met>:
        counter += 1
    rec_func(m,n)
    rec_func(j,k)
    return counter

counter = 0
print funct(q)

上面的代码做了我需要的。但是由于代码运行的一些限制,我不能将“计数器”定义为全局。有没有其他方法可以在没有全局变量“counter”的情况下实现这一点

注意:递归函数在该函数中被调用两次。所以我需要一种方法来提供从一个到下一个的计数。

标签: python-2.7dynamic-programming

解决方案


如果您真的不想将变量“counter”设为全局变量,只需将其作为参数传递给函数的参数。在这段代码中,我调用函数“call_recursive”,该函数调用“recursive_function”参数 x = 5 和 counter = 0 并且函数将调用自身 5 次并且 x 将递减。X 将在达到 0 后停止并返回计数器。我希望它有所帮助。

def call_recursive(x):
    counter = 0
    return recursive_function(x, counter)

def recursive_function(x, counter):
    if(x != 0):
        counter += 1
        return recursive_function(x - 1, counter)
    else:
        return counter


x = 5
print(call_recursive(x))

推荐阅读