- bikermiker

In the Spring 2013 Edition of this book, on page 50, figure 4.10. This code for the Fibonacci sequence is give.
def fib(x):
"""assumes x an int >= 0 returns Fibonacci of x """
global numCalls
numCalls += 1
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
def testFib(n):
for i in range(n+1):
global numCalls
numCalls = 0
print 'fib of ', i, '=', fib(i)
print 'fib called', numCalls, 'time.'
Is there an error. Should numCalls = 0 ?

- jamiebookeater

I got my questions answered at brainly.com in under 10 minutes. Go to brainly.com now for free help!

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.

Get this expert

answer on brainly

SEE EXPERT ANSWER

Get your **free** account and access **expert** answers to this

and **thousands** of other questions

- e.mccormick

Yes. It needs to be reset every time you test it.

- e.mccormick

See, they are using a global to keep track of the number of calls for each Fibonacci sequence it generates. Every time it advances, it resets the number of calls so that you see the number of calls for only that particular run.

- bikermiker

I don't see what you mean. Wouldn't it make more sense to move the global numCall out of both functions entirely and just keep numCall +=1 in each function. Then it'll count how many times it calls the variable for each function.

Looking for something else?

Not the answer you are looking for? Search for more explanations.

## More answers

- e.mccormick

You would still need to reset it inside the test function. They don't seem to want the grand total for all sequences. Just a total for one sequence at a time.

- bikermiker

So it's correct when numCalls always comes up as 1. If I had this function run twice, within a larger function then numCalls should come up as 2?

- e.mccormick

It would come up as different values depending on the size of the tested range.

- e.mccormick

do testFib(5)

- bikermiker

fib(5) = 8, when I print numCalls it comes up as 1, which is what it comes up as when I run testFib

- e.mccormick

```
def fib(x):
"""assumes x an int >= 0 returns Fibonacci of x """
global numCalls
numCalls += 1
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
def testFib(n):
for i in range(n+1):
global numCalls
numCalls = 0
print 'fib of ', i, '=', fib(i)
print 'fib called', numCalls, 'time.'
testFib(5)
```
gets me:
```
*** Python 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)] on win32. ***
*** Remote Python engine is active ***
>>>
*** Remote Interpreter Reinitialized ***
>>>
fib of 0 = 1
fib called 1 time.
fib of 1 = 1
fib called 1 time.
fib of 2 = 2
fib called 3 time.
fib of 3 = 3
fib called 5 time.
fib of 4 = 5
fib called 9 time.
fib of 5 = 8
fib called 15 time.
>>>
```

- bikermiker

See now that makes sense, but that's not what I'm getting. I get an error when I use the program verbatim from the book.

- e.mccormick

What version of Python are you using?

- bikermiker

2.5.4

- e.mccormick

Hmmm.... Just ran it on 2.5
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
```
def fib(x):
"""assumes x an int >= 0 returns Fibonacci of x """
global numCalls
numCalls += 1
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
def testFib(n):
totalCalls = 0
for i in range(n+1):
global numCalls
numCalls = 0
print 'fib of ', i, '=', fib(i)
print 'fib called', numCalls, 'time.\n'
totalCalls = totalCalls + numCalls
print "Total of all calls is: ", totalCalls
testFib(5)
```
and got:
```
>>>
fib of 0 = 1
fib called 1 time.
fib of 1 = 1
fib called 1 time.
fib of 2 = 2
fib called 3 time.
fib of 3 = 3
fib called 5 time.
fib of 4 = 5
fib called 9 time.
fib of 5 = 8
fib called 15 time.
Total of all calls is: 34
>>>
```

- bikermiker

I think I got it. numCalls = 0 goes in both functions. fib only gives me the number in the sequence and testFib, gives me the fib sequence and the number of times it has been called. I had removed numCalls = 0 from the testFib function. Now I'm getting what you're getting.

- bikermiker

That's the error in the book you mentioned?

- e.mccormick

I do not have numCalls = 0 in both. I see no error.

- bikermiker

def fib(x):
"""assumes x an int >= 0 returns Fibonacci of x """
global numCalls
numCalls = 0
numCalls += 1
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
def testFib(n):
for i in range(n+1):
global numCalls
numCalls = 0
print 'fib of ', i, '=', fib(i)
print 'fib called', numCalls, 'time.'

- bikermiker

It only runs def fib(x) when I use numCalls= 0, otherwise I get an error.

- e.mccormick

With it using a global in the way it is, you can NOT do fib(5) directly. You MUST use it through the test harness or some other method that creates the global properly so that there is not an error.

- e.mccormick

Some comments as to what happens:
```
def fib(x):
"""assumes x an int >= 0 returns Fibonacci of x """
global numCalls # This line tells it that a global will be used.
numCalls += 1 # This line uses a global, but only works if the global exists.
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
def testFib(n):
totalCalls = 0
for i in range(n+1):
global numCalls # This line tells it that a global will be used.
numCalls = 0 # This line defines/creates the global.
print 'fib of ', i, '=', fib(i)
print 'fib called', numCalls, 'time.\n'
totalCalls = totalCalls + numCalls
print "Total of all calls is: ", totalCalls
```

- bikermiker

You are correct, if I run testFib first and the fib, I get no errors and the correct answer for both, when using the code verbatim from the book.

- bikermiker

Gotcha, now it makes sense.
Thanks so much for the help and have a nice day.

- e.mccormick

It always takes people a little but to get one concept or another. This one is a key one in computing. Fariables must be declared before they canbe used. Python is more forgiving about this, but the rule still applies.
In python:
```
x = 5
print x
````
That works. But in Java:
```
x = 5;
System.out.println(x);
```
would fail because you would need to tell it that x is an integer (number).
```
int x;
x = 5;
System.out.println(x);
```
or:
```
int x = 5;
System.out.println(x);
```
Would be the fix in java. Same basic issue you were having, I would be using it before defining it.

- e.mccormick

Ooops.... I mised one of the ``` sets so my code blocks are messed up. LOL

- bikermiker

No worries, but I see exactly what you mean. For some reason it just never occurred to me to run a program to define or declare a variable. Thanks.

- e.mccormick

Guntag loves using a test harness for his stuff. I can understand why. It is more like how real world programming is done.

- e.mccormick

https://en.wikipedia.org/wiki/Test_harness

- bikermiker

Given all the nuances that can cause an error, including user error, it makes sense.

- bikermiker

Once again thanks for the help and take care.

Looking for something else?

Not the answer you are looking for? Search for more explanations.