For the purpose, we were asked to define the fibonacci function, which I performed using this:
def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)
However, I saw recursive functions, such as a factorial function, defined on a single line, returning an operator as follows:
def factorial(n): return n > 1 and n * factorial(n-1) or 1
So, I tried to apply the same to my fibonacci function. After several attempts, I got it to work in all verified cases, except when s = 0, in which case it returns False, when it should return 0. Here is where I am:
def fibonacci(n): return ((n == 0 or n == 1) and n) or (n > 1 and (fibonacci(n-1) + fibonacci(n-2)))
I understand that python evaluates from 0 to False, so how could I return python instead of False when n is 0, keeping the current code length / structure? Is it possible?
In addition, is this style of function creation (recursive or otherwise) more or less desirable / pythonic than the textbook version? (I would suggest not only because of readability)
To be clear, I satisfied the requirements for the task and only for personal knowledge, I would like to get a clearer idea of โโwhat is happening in the return statement.