Check input belonging to Fibonacci numbers in Python

I would like to ask how I can retrieve a Fibo list, and then check if the input value by the user is inside the Fibo list.

a , b = 1, 1 while num <= sys.maxint: fibo == a , b = b, a+b if num == (b +a+b): print "It is a Fibonacci number" break else: print "It is not a Fibonacci number" break 

Thanks!

+4
source share
4 answers

Using a more sophisticated Fibonacci test , you can use

 def is_fibonacci(n): phi = 0.5 + 0.5 * math.sqrt(5.0) a = phi * n return n == 0 or abs(round(a) - a) < 1.0 / n 

(This is probably the most effective way to determine if a number is a Fibonacci number, and it most likely is not intended for your homework. I just included this answer for future reference.)

+8
source

Pythonic single line

 def is_fibonacci(n): return n >= 0 and (n==0 or sqrt( 5*n*n - 4).is_integer() or sqrt( 5*n*n + 4).is_integer()) 
+3
source

Perhaps not a very effective solution - using the close formula is more efficient (see Sven answer ), but you can do this:

 def fibs(): a,b = 0,1 yield a yield b while True: a,b = b,a+b yield b n = int(raw_input("please, enter a number ")) for fib in fibs(): if n == fib: print "your number is a Fibonacci number!" break if fib > n: print "your number is not a Fibonacci number!" break 

The fibs generator gives you a list of Fibonacci numbers. You can view the list, and each number that you can check whether it matches the user entered (in this case you finished), or if it is larger than the one entered by the user (and also made in this case).

Hope this is helpful, at least for understanding Python generators.

+1
source
 x = int(input("Enter a number: ")) A = [0, 1] for i in range(2,720): A.append(A[i-1]+A[i-2]) bool=False for i in range(2,720): if x==A[i]: bool=True break if bool==True: print "Found,Index is:",i+1 else: print "Not Found" 
0
source

All Articles