递归累积或如何计算Python中递归调用的数量?
我已经阅读了很多Python手册,但无法理解这个 函数中的两个局部变量调用自身,其中只有一个行为类似于“静态” 下面是代码片段:递归累积或如何计算Python中递归调用的数量?,python,algorithm,recursion,static,Python,Algorithm,Recursion,Static,我已经阅读了很多Python手册,但无法理解这个 函数中的两个局部变量调用自身,其中只有一个行为类似于“静态” 下面是代码片段: def sort_bubble(local_itera, difficulty): #local_itera = itera[:] sorted_count = 0 nrecursions = 0 for i in range(difficulty - 1): val1 = local_itera[i]
def sort_bubble(local_itera, difficulty):
#local_itera = itera[:]
sorted_count = 0
nrecursions = 0
for i in range(difficulty - 1):
val1 = local_itera[i]
val2 = local_itera[i+1]
if local_itera[i] == min(val1, val2):
sorted_count += 1
continue # skip sorted pairs
else: # swap
local_itera[i] = min(val1, val2)
local_itera[i+1] = max(val1, val2)
if not sorted_count == difficulty - 1: # recurse if not sorted
nrecursions += 1
sort_bubble(local_itera, difficulty)
当sorted\u count
增加时,nrecursions
不增加,我想用它来计算递归调用的数量
请注意,本文件的目的是
作为一个自包含的功能(这只是原型):
- 全局变量无法达到目的
- 类语法开销与此目的背道而驰
但这也太过分了。问题似乎在于,与排序计数不同,您没有在任何地方增加对函数的调用次数。要计算递归的数量,您需要适当地增加它[操作说明:问题更新] 此外,在每次函数调用期间,
nRecursion
将被重新初始化为0,因为您已将其放置在函数中。因此,应该在函数外部将其初始化为0
在我看来,这是如下增加它的正确位置。此外,您需要使变量类型为全局
nrecursions = 0
def sort_bubble(local_itera, difficulty):
global nrecursions
# Function body
if not sorted_count == difficulty - 1: # recurse if not sorted
nrecursions += 1 # <--- added here
sort_bubble(local_itera, difficulty)
nrecursions=0
def排序气泡(局部气泡,难度):
全局递归
#功能体
如果未排序_count==难度-1:#如果未排序则递归
nrecursions+=1#修复代码中的缩进,并解释问题的确切位置以及所指的变量nrecursions
应在递归函数外部初始化一次,在递归函数内部简单递增。顺便说一句,没有变量表现为静态的,函数体内的sorted_count
和nRecursion
都一直在初始化,并获取一些值,这些值不是从调用中保留的,因为它获取了一些值(在单个递归调用期间),该值根据if..
测试停止递归。没有魔法,它很简单。在任何情况下,它都不会将其值保留在cal中,以便在每次调用函数时重新初始化它。很明显,我链接到@AgnesK.Cathex的副本上还有其他选项。例如,您可以简单地创建一个可调用对象的类。这是自包含的,但为您提供了局部静态变量。不,@AgnesK.Cathex。可以调用,因为可以将类实例用作函数。不过,您可能可以让yield
为您工作。这个问题解决了sorted\u count
也在主体中初始化的事实。@AgnesK.Cathex:您不应该在函数中初始化递归变量。想想看,一旦你再次调用它,变量就被设置为零,所以你永远不会得到任何结果increment@ChristianDean:我认为只要在函数中使用nrecursions
的更新值,就可以了。只有在退出函数后使用if时,才需要将其定义为全局,否则在函数外它将始终为0。对吧?@ChristianDean:Done@ChristianDean:完成
nrecursions = 0
def sort_bubble(local_itera, difficulty):
global nrecursions
# Function body
if not sorted_count == difficulty - 1: # recurse if not sorted
nrecursions += 1 # <--- added here
sort_bubble(local_itera, difficulty)