hkn-a - 1 year ago 81
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 ?

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:

fibonacci_sequence = []

for value in range(10):
fibonacci_sequence.append(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.

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():