python 递归函数没有输出

Nothing is output in python recursive function

我正在编写计算翻转立方体两个配置之间的 'distance' 的代码,两个配置 x 和 y 之间的距离是从 x 到 y 所需的最少步数,或者相反。

为了做到这一点,我创建了一个更简单的版本,使某些东西有所不同,此代码采用两个整数 cicf。使用 ci returns 一个名为 main_level 的迭代器通过名为 multi 的生成器,然后,只要 cf 不在 [= 中,它就会遍历搜索参数 cf 81=] 变量 steps 增加 1,对于 main_level 中的每个元素,我们重复相同的过程ci 完成。最后,当 cii==cf 程序结束并且 returns 变量 steps我们必须向下找到给定参数 cf 的“级别”。这段代码没有任何实际用途,只是我上面提到的问题的基础。

如果我用 ci=5 调用 distance(ci, cf) 函数,前两个级别是:

{0,3,6,9,12} <-- 第一级(步数初始化为1) 如果 cf 是集合中的任何数字,程序应该结束并且 return steps=1, 如果 cf 不在该集合中,则程序构成第二级: {15,18,21,24,27,30,33} 并搜索 cf,如果 cf有,程序结束,应该returnsteps=2,如果没有,则形成第三层,以此类推。但是实际上有一个问题,当我用 ci=5 和 cf= 任意自然数调用距离函数时,并且打印它的值,什么都输出,只有cf=0,它输出step=1。我真的不知道发生了什么。我很感激ci得到你的帮助。

代码如下:

#Base solution to FlipCube problem

def multi(par):
   for i in range(par):
     yield i*3    

steps=1 

def distance(ci,cf):
    main_level =set(multi(ci))
    global steps  

    def check_main_level(cf):
        global  steps 
        nonlocal  main_level
        
        def lower_level(config_list):
            sett=set()
            for i in config_list:
               sett.update(q for q in multi(i) if q not in config_list)
            nonlocal  main_level
            main_level=sett
            check_main_level(cf)  

        for i in main_level:
            if i==cf:
                break
            else:
                steps+=1
                lower_level(main_level)
    check_main_level(cf)              
    return steps  
    
#testing
e=  distance(5,0)
print(e)# prints 1, very good
e2=  distance(5,9)
print(e2)# should print  1, but doesn't print anything :(
e3=  distance(5,27)
print(e3)# should print  2, but doesn't print anything :(

你有一个无限循环,这就是什么都不打印的原因。

你可以通过添加打印轻松看到它:

for i in config_list:
               print(i)
               sett=set()
               sett.update(q for q in list(multi(i)) if q not in config_list)

程序不会在所有情况下终止递归。罪魁祸首似乎是 check_main_level 中的 for 循环。将 lower_level 定义后的代码更改为:

# code portion of check_main_level
        if cf > max(main_level):
            steps+=1
            lower_level(main_level)
# end of code portion check_main_level (replacing for-loop)