1

I'm tackling this following question:

Write a function is_fib(n) that returns True if n is a Fibonacci number, and False otherwise.

This is my code:

def is_fib(n):
    def fib(x):
        if x == 0:
            return 0
        elif x == 1:
            return 1
        else:
            return fib(x-1) + fib(x-2)
    for a in n:
        if fib(a) == n:
            result = True
            break
        else:
            result = False
    return result

Running this give rise to:

TypeError: 'int' object is not iterable.

I have been staring at the code for half an hour. Any help is greatly appreciated.

3 Answers 3

1

I think you mean

for a in range(n)

not

for a in n
Sign up to request clarification or add additional context in comments.

Comments

0

As jozefg said you are missing range(n)

also notice that you need range(n+2) to cover all cases

def is_fib(n):
    def fib(x):
        if x == 0:
            return 0
        elif x == 1:
            return 1
        else:
            return fib(x-1) + fib(x-2)
    for a in range(n+2):
        if fib(a) == n:
            return True


    return False

print(is_fib(3))

Comments

0

Firstly thanks to the two guys that helped me. However, for Yoav's edition, python will run into an error when n is a really big number.

This is my new and improved version.

def is_fib(n):
    if n < 0:
        return False
    else:
        fib_0 = 0
        fib_1 = 1
        if n == fib_0 or n == fib_1:
            return True
        else:
            for a in range(2,n+2):
                fib = fib_0 + fib_1
                fib_0,fib_1 = fib_1,fib
                if fib >= n:
                    break
            return fib == n

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.