0

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.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
Spuddy
  • 19
  • 4
  • Please, type as text the content of the image – cards Mar 24 '23 at 19:56
  • Hint: `return Euclidean_algorithm(b, a, verbose)` will become `return 1 + number_of_steps_EA(b, a)` – Brian61354270 Mar 24 '23 at 19:56
  • 1
    return a list and then look at its length – cards Mar 24 '23 at 20:00
  • Modify the Euclidean_algorithm(a,b) function to create a function number_of_steps_EA(a,b) which returns the number of steps that the Euclidean algorithm requires, i.e., the number of divisions-with-remainder. (for the first comment) – Spuddy Mar 24 '23 at 20:09
  • The function isn't recursive, except the initial check to fix the order of arguments. So the number of steps can only be calculated by incrementing a counter in the `while` loop. I don't see any way to do this external to the function as written. – Barmar Mar 24 '23 at 20:58

1 Answers1

0

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
Alain T.
  • 40,517
  • 4
  • 31
  • 51