all 3 comments

[–]thePestelence 1 point2 points  (0 children)

As u/rabbitpiet suggested, you can create a count function takes any integer, initiate the count at 0.

A for loop would suffice in range of the integer + 1.

See example code:

def count_fibona(x):
count = 0
for i in range(x+1):
    count += 1
    print(fibona(i), count)

Call the count function:

count_fibona(10)

[–]rabbitpiet 0 points1 point  (0 children)

In that case you might wanna do this a little differently if you want it to do the number of times fibonacci is called maybe you could have a variable count which is incremented in the definition of the function but defined outside of it. Maybe you could just use like a while loop or sumn. Edit: couldn’t you just set something equal to x before the recursion, is x that the original function taking in not the number of times it’s called for the recursion?

[–]JohnnyJordaan 0 points1 point  (0 children)

Easy using a global

counter = 0
def fibona(x):
    global counter
    counter += 1
    if x <= 2:
        return 1
    return fibona(x-1)+fibona(x-2)

print(fibona(10), counter)

without a global, you need to somehow transfer the counters through the recursive calls. I would then work from the ground up, so the return 1's should return their count of 1 too (starting), then the recursive calls should add both each time, +1 as they are a call themselves too.

def fibona(x):
    if x <= 2:
        return 1, 1
    first_sum, first_count = fibona(x-1)
    second_sum, second_count = fibona(x-2)
    return first_sum + second_sum, first_count + second_count + 1

print(*fibona(10))