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 resultYou 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 resultIn 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