hkn-a hkn-a - 2 months ago 20
Python Question

Is it valid to write some code that a bit tricky as long as I get same result (fibonacci in python)

In Pycharm Edu I've encountered with this code:

def fib(n):
"""This is documentation string for function. It'll be available by fib.__doc__()
Return a list containing the Fibonacci series up to n."""
result = []
a = 1
b = 1
while a < n:
result.append(a)
tmp_var = b
b = a+b
a = tmp_var
return result


Since I am still learning I tried to do something similar with lists but the problem is to get a proper fibonacci series I used [-1,1] to start calculation, but results are same. Here is my code:

x = [-1,1]

y = []

for i in range(10):
c = x[0] + x[1]
y.append(c)
x[0] = x[1]
x[1] = c

print(y)


The question is, can I get away with this ?

Answer

This question might be too opinion-based for this site, but take into consideration that your code doesn't just need to run, it also needs to be readable. Otherwise, what you have written is entirely valid.

Consider this:

addends = [-1,1]

fibonacci_sequence = []

for value in range(10):
    next_fibonacci = addends[0] + addends[1]
    fibonacci_sequence.append(next_fibonacci)
    addends[0] = addends[1]
    addends[1] = next_fibonacci

print(fibonacci_sequence)

As I said, this may seem like opinion, but make sure you keep the beginning PEP 20 in mind:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts...

As a final note, your code is not a function, but the original code snippet is a function. Here is your code as a function:

def fibonacci():
    addends = [-1,1]

    fibonacci_sequence = []

    for value in range(10):
        next_fibonacci = addends[0] + addends[1]
        fibonacci_sequence.append(next_fibonacci)
        addends[0] = addends[1]
        addends[1] = next_fibonacci

    return fibonacci_sequence

print(fibonacci())