user3517740
user3517740

Reputation: 47

Counting the number of recursion of a function within the function

I am working on this function and WITHIN the function I would like to count the number of iterations/recursions of the function in itself. Any and all help would be helpful! Thank you!

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

Upvotes: 0

Views: 429

Answers (2)

user3517740
user3517740

Reputation: 47

I think I got it!

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 )

Upvotes: 0

Blckknght
Blckknght

Reputation: 104712

You could pass a count argument up your recursive chain:

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

This program really doesn't need to be recursive though. An iterative solution would be:

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

Upvotes: 3

Related Questions