How to find the nearest Fibonacci Series number?

后端 未结 4 1058
耶瑟儿~
耶瑟儿~ 2020-12-04 03:16

My next step is if the input is not in the Fibonacci Series, the program has to give an output with a number which is in the series that is nearest to the input. I do not kn

4条回答
  •  半阙折子戏
    2020-12-04 04:07

    You could zip fibs with itself:

    n = int(input("please, enter a number: "))
    for fib, next_fib in itertools.izip(fibs(), itertools.islice(fibs(), 1, None)):
        if n == fib:
            print("Yes! Your number is a Fibonacci number!")
            break
        if next_fib > n:
            closest = fib if n - fib < next_fib - n else next_fib
            print("The closest Fibonacci number is {}".format(closest))
            break
    

    You could use itertools.tee to optimize it a bit.

提交回复
热议问题