Python syntax: how to return 0 instead of false when evaluating 0

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.

+4
source share
2 answers

The idiom x and y or z does not work if y false . You can change the condition to make it work, however:

 def fibonacci(n): return n >= 2 and fibonacci(n-1) + fibonacci(n-2) or n 

However, with Python 2.5 (released 6 years ago), we have proper conditional expressions and no need to crack and/or longer:

 def fibonacci(n): return n if n < 2 else fibonacci(n-1) + fibonacci(n-2) 

Now it has exponential complexity of execution. If you want to be efficient, use the O(n) algorithm:

 def fibonacci(n): a, b = 0, 1 for _ in range(n): a, b = b, a + b return a 

Or even write a generator to get all the numbers and use only as much as you need.

+10
source

Perhaps this makes it clearer:

 def fibonacci(n): print ((n == 0 or n == 1) and n) print (n > 1 and (fibonacci(n-1) + fibonacci(n-2))) return ((n == 0 or n == 1) and n) or (n > 1 and (fibonacci(n-1) + fibonacci(n-2))) print 0 or False print False or 0 
+1
source

Source: https://habr.com/ru/post/1411613/


All Articles