python-2.7 - 多重递归内的计数器
问题描述
所以我正在编写一个具有多个递归函数调用的代码。而且我想在满足某些条件时增加一个计数器。
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”的情况下实现这一点
注意:递归函数在该函数中被调用两次。所以我需要一种方法来提供从一个到下一个的计数。
解决方案
如果您真的不想将变量“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))
推荐阅读
- javascript - 将 React 状态对象转换为正确的 JSON 模式
- c# - ASP.NET Razor 页面错误:InvalidOperationException:不正确的内容类型
- php - 将脚本从 MySql PDO & INSERT 更改为 PostGRESql
- python - 获取字典映射值到引用 ID
- c++ - 子进程退出后,来自匿名管道的 ReadFile 不返回
- javascript - 如何安全地设置 Facebook Web SDK
- javascript - 尝试将映射键转换为数组时遇到错误
- php - PHP最佳实践显示包含大量行数的文件中的所有行
- laravel - 管理面板中带孩子的模型的 UX
- php - 获取多维数组