Trying to write a code to findout how many times a function has been called upon

38 Views Asked by At

I have a two part Question where the first part was to write a code using the Euclidean algorithm function for two numbers. This was the code i made, it works:

from math import *
def Euclidean_algorithm(a, b, verbose = True):
    if a < b:
        return Euclidean_algorithm(b, a, verbose)
    
    print()
    while b != 0:
        if verbose: print('%s = %s * %s + %s' % (a, floor(a/b), b, a % b))
        (a, b) = (b, a % b)
            
    if verbose: print('The GCD is %s' % a)
    return a

For the second part, was to attach a function of "number_of_steps_EA(a,b)" to it to track and display at the end how many times the function was used until the GCD was found, but i don't have an idea of code behind the function as i know about the global counter method (not sure how to code that) but i'm not sure if the global counter is used in the function of "number_of_steps_EA(a,b)". Sorry if this makes little sense. If asked, i'll try to explain the best i can. enter image description here I've looked at other questions about this but none use this "number_of_steps_EA" so i got confused. The image is of the question on my sheet.

1

There are 1 best solutions below

0
Alain T. On

You could write a small decorator and add it to the definition of your function.

For example:

def countCalls(f):
    f.count = 0
    def countedCall(*args,**kwargs):
        f.count += 1
        return f(*args,**kwargs)
    countedCall.call = f
    return countedCall

usage:

@countCalls
def gcd(a,b):
    return b if a<1 else gcd(b%a,a)

print(gcd(122,348))    # 2
print(gcd.call.count)  # 7

gcd.call.count = 0
print(gcd(12345,67890)) # 15
print(gcd.call.count)   # 4