Tammy
Tammy

Reputation: 131

Python (Position of Fibonacci Number)

I have figured out the code for finding Fibonacci Numbers. If the input is not a fibonacci number, the program will print out the nearest number. Next, how do I determine the position of that number in the series? Like if n = 8, it's position is 7th, so the output is 7. I tried to use index, but python states that index is not applicable to integer

def fibs():
    a,b = 0,1
    yield a
    yield b
    while True:
        a,b = b,a+b
        yield b

def nearest_fib(n):
    # If n is a Fibonacci number return Yes and n
    # Otherwise, return No and the nearest Fibonacci number

    n = int(input("Please enter an integer:"))
    for fib in fibs():
        if fib == n:
            return print("Yes! your integer is an fibonacci number")
        elif fib < n:
            prev = fib
        else:
            # Is n closest to prev or to fib?
            if n - prev < fib - n:
                return print("No! Your answer is not a fibonacci number"), prev
            else:
                return print("No! Your answer is not a fibonacci number"), fib

for i in range(1):
    print(i,nearest_fib(i))

Upvotes: 0

Views: 1641

Answers (1)

jez
jez

Reputation: 15349

Use enumerate, which will give you an index as well as a value:

 for ind, fib in enumerate(fibs()):

Store both the index and the value where you currently store prev:

def fibs():
    a,b = 0,1
    yield a
    yield b
    while True:
        a,b = b,a+b
        yield b

def nearest_fib(n):
    #If n is a Fibonacci number return Yes and n
    #Otherwise, return No and the nearest Fibonacci number

    for ind, fib in enumerate(fibs()):
        if fib == n:
            print("Yes! your integer is fibonacci number #%d" % (ind + 1) )
            return n
        elif fib < n:
            prev_index = ind
            prev = fib
        else:
            # Is n closest to prev or to fib?
            if n - prev < fib - n:
                print("No! Your answer is not a fibonacci number. It is closest to number #%d" % (prev_index + 1))
                return prev
            else:
                print("No! Your answer is not a fibonacci number. It is closest to number #%d" % (prev_index + 2))
                return fib

for i in range(10):
    n = int(input("Please enter an integer:"))
    print(n,nearest_fib(n))

Upvotes: 1

Related Questions