【问题标题】:Counting the number of recursion of a function within the function计算函数内函数的递归次数
【发布时间】:2014-06-08 23:27:39
【问题描述】:

我正在研究这个函数,并且在函数内部我想计算函数本身的迭代/递归次数。任何和所有的帮助都会有所帮助!谢谢!

def runGenerations( L ):
    """ runGenerations keeps running evolve...
    """

    count = 0
    show(L)
    print(L)
    time.sleep(0.05)  

    if allOnes(L) == True:

        return L


    else:

        newL = evolve( L ) 
        return runGenerations( newL ) + 1

【问题讨论】:

  • 您需要以某种方式保持状态,我不确定您对“WITHIN”的定义是什么,但是否可以为计数添加一个新参数?
  • 我的意思是我不想添加 count 作为另一个变量,比如将函数更改为 runGenerations(L,count)

标签: python function recursion iteration


【解决方案1】:

您可以在递归链上传递 count 参数:

def runGenerations(L, count=1):
    show(L)
    print(L)

    if allOnes(L):
        print("result found after {} attempts".format(count))
        return L

     newL = evolve(L)
     return runGeneratons(newL, count+1) + 1

不过,这个程序确实不需要递归。一个迭代的解决方案是:

def runGenerations_iterative(L):
    count = 1
    show(L)
    print(L)

    while not allOnes(L):
        L = evolve(L)
        count += 1
        show(L)
        print(L)

    print("result {} found after {} attempts".format(L, count))
    return L + count - 1

【讨论】:

  • 要记住的另一件事是 Python 有递归深度限制。我认为默认设置为 1000。请参阅 sys.getrecursionlimit()sys.setrecursionlimit()
  • @blckknght 有没有办法在不使用格式(计数)的情况下做到这一点?
  • @mtadd 我把限制调高了,但是谢谢你的警告!
  • @user3517740:您的意思是,您可以返回计数而不是打印它吗?我想你可以,虽然它会使返回最终的L 值在递归版本中更加复杂。您是否有理由在每个级别上增加返回值?这对我来说没有多大意义(但是,我不知道 L 的值是什么)。
  • @blckknght 我正在制作一个涉及另外两个的函数:setNewElement:setNewElement 返回新列表的第 i 个元素,其中它是 0 或 1(随机选择)进化:~它需要一个列表整数并使用其中的 setNewElement 函数通过使用列表推导向列表中的每个元素添加一个来创建新列表。因此,原始列表中的每个元素都增加了一个。 runGenerations:~基本上这个函数让进化一直持续到列表包含所有的人
【解决方案2】:

我想我明白了!

def runGenerations( L ):
    """ runGenerations keeps running evolve...
    """

    count = 0
    show(L)
    print(L)
    time.sleep(0.05)  

    if allOnes(L) == True:

        return 0


    else:

        newL = evolve( L ) 
        return 1 + runGenerations( newL )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-04
    • 2021-07-24
    • 2022-11-25
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    相关资源
    最近更新 更多