【问题标题】:Nothing is output in python recursive functionpython递归函数中没有任何输出
【发布时间】:2021-05-17 19:00:48
【问题描述】:
  • 列表项

我正在编写一个代码来计算翻转立方体的两个配置之间的“距离”,两个配置 x 和 y 之间的距离是从 x 到 y 所需的最小步数,反之亦然。

为了实现这一点,我创建了一个更简单的版本,使之与众不同,这段代码采用两个整数 cicf。 with ci 通过名为 multi 的生成器返回一个名为 ma​​in_level 的迭代器,然后遍历它以搜索参数 cf,只要 cf 不在 ma​​in_level 中,变量 steps 就会增加 1,并且对于 ma​​in_level 中的每个元素我们对 ci 重复相同的过程。最后,当 cii==cf 程序结束并返回 steps 变量,该变量计算我们必须向下找到给定参数的“级别”数cf。这段代码没有任何实际用途,只是我上面提到的问题的一个基础。

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

{0,3,6,9,12} cf 是集合中的任何数字,则程序应结束并返回 steps=1, 如果 cf 不在该集合中,则程序形成第二级: {15,18,21,24,27,30,33} 并搜索 cf,如果有 cf,则程序结束并应返回steps=2,如果不是,则形成第三级,以此类推。但是有一个问题,实际上,当我用 ci=5 和 cf= 任意自然数调用距离函数,并打印它的值时,输出任何东西,仅用于cf=0,输出step=1。我真的不知道发生了什么事。非常感谢您的帮助。

代码如下:

#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 :(

【问题讨论】:

    标签: python python-3.x recursion global-variables iterable


    【解决方案1】:

    程序在任何情况下都不会终止递归。罪魁祸首似乎是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)
    

    【讨论】:

      【解决方案2】:

      你有一个无限循环,所以什么都没有打印出来。

      您可以通过添加打印轻松查看:

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

      【讨论】:

        猜你喜欢
        • 2021-12-10
        • 1970-01-01
        • 2023-01-25
        • 2020-12-23
        • 2011-11-17
        • 1970-01-01
        • 1970-01-01
        • 2013-10-13
        相关资源
        最近更新 更多