Pages

A Python function

In the official Python tutorial as an example of function is showed a piece of code that calculate the Fibonacci series. Among the language features on display there, we can also see the handy way of assigning values to more variables in a single operation. Reading it, I though "Cool. But we don't really need two of them there".

So, just for the fun of it, I refactored the function to get rid of the extra variable.

Here is the original code, as you can find it on the python.org tutorial page:
def fib2(n):
    result = []
    a, b = 0, 1
    while a < n:
      result.append(a)
      a, b = b, a+b
    return result
You see the point. It is nice to initialize and modify a and b in the same line, since they are so strictly connected. However, just a single buffer integer is required, since we can refer to the list we are going to return. Well, at least if we can assume that the user won't pass as parameter a value less than one.
def fibonacci(n):
    result = [0]
    candidate = 1
    while candidate < n:
        result.append(candidate)
        candidate += result[-2]
    return result
In comparison with the original function, my version loose the example of comma-assignment functionality. However I use the increase-assign (+=) operator and the negative index support on list. I would say it is a tie.

No comments:

Post a Comment