It is necessary to determine whether a number is a Fibonacci element using lambda, True / False.

There is a code fib = lambda n, a=1, b=2: int(((a + 5**0.5)**n - (b - 5**0.5)**n) / (b**n * 5**0.5)) Which only displays the element.

It is the same here, but I am not sure that it is possible to unpack the type a, b = b, a + b in anonymous functions.

 def fib(n): a, b = 0, 1 for __ in range(n): a, b = b, a + b if n == b: return True return False print(fib(144)) 

    2 answers 2

    One of the properties of the Fibonacci number :

    A natural number N is a Fibonacci number if and only if 5N ^ 2 + 4 or 5N ^ 2-4 is a square. A square number is a number that is the square of an integer.

    So this is a bit cumbersome code:

     from math import sqrt fib = lambda n: True if sqrt(5*(n**2)-4)%1 == 0 or sqrt(5*(n**2)+4)%1 == 0 else False fib(5) # True fib(14) # False fib(4181) # True 

    What is happening in it?

    1. We calculate the sqrt(5*(n**2)-4) and sqrt(5*(n**2)+4) values ​​and find the remainder of dividing by 1. In case one of the values (5*(n**2)-4) or (5*(n**2)+4) is a square, then the square root of such a number is a natural number and, therefore, the remainder of dividing by 1 will be equal to 0.
    2. Accordingly, then we check the remainder of the division. If one of the residues is 0, we print True , otherwise False

    Thus, when checking it is not necessary to calculate the Fibonacci series every time.

    • one
      fib = lambda n: sqrt(5*(n**2)-4)%1 == 0 or sqrt(5*(n**2)+4)%1 == 0 - gil9red

    This is the function obtained:

     is_fibo = ( lambda a: lambda v,fib=0,n=1: a(a,v,fib,n) )( lambda f,value,fib,n: f(f,value,fib+n,fib) if fib < value else fib==value ) >>> is_fibo(7) False >>> is_fibo(8) True 
    1. The first lambda on the left defines a function with one parameter a , which is a function
    2. The second left lambda has 3 parameters, 2 of them are optional, and consists of a recursive call to the first lambda
    3. This construction is executed and as parameters it receives the third lambda function, which is directly involved in calculating Fibonacci numbers and comparing with a given value.
    4. When executing the function obtained, all the arguments, except the value , are already defined. Here we set the value when calling is_fibo(..)
    5. Next, we recursively calculate the Fibonacci numbers until the next number is greater than or equal to our value argument. After that, we return the result of comparing the Fibonacci number and the argument