+ 1
Para que es el range(n-3) --> For that is range(n-3)
def fibonacci(n): a = 1 b = 1 if n == 1: print('0') elif n == 2: print('0', '1') else: print('0') print(a) print(b) for x in range(n-3): total = a + b b = a a = total print(total) print(fibonacci(6))
2 Answers
+ 1
[a rough translation of my previous answer using google translate]
Comprueba primero si el argumento (nĂşmero de fibonacci a imprimir) dentro de la funciĂłn fibonacci() es 1 o 2 o mĂĄs de 2.
Por ejemplo:
fibonacci(1)
đ¸ la primera condiciĂłn es verdadera, asĂ que imprime '0'
>> 0
fibonacci(2)
đ¸ segunda condiciĂłn Verdadero asĂ que imprime '0' y '1'
>> 0 1
fibonacci(5)
đ¸ ambas condiciones son falsas
đ¸ proceder al bloque else
đ¸ imprimir 0, 1, 1 consecutivamente
đ¸ for x in range(n-3) tambiĂŠn se convertirĂĄ en for x in range(2) ya que 5-3 es 2
đ¸ HabrĂĄ dos iteraciones para calcular los prĂłximos nĂşmeros de Fibonacci (suma del nĂşmero actual y la suma anterior).
>> 0 1 1 3 5
đš 0 1 1 se imprimiĂł manualmente y 3 5 se calculan dentro del ciclo for
TIP: puede acortar este cĂłdigo si reemplaza el rango (n-3) con el rango (n) y reemplaza el valor de a por 0, lo que hace innecesarias las dos condiciones si elif, ya que puede hacer todos los cĂĄlculos dentro del bucle for para todos los nĂşmeros.
0
It checks first if the argument (number of fibonacci to be printed) inside fibonacci() function is 1 or 2 or more than 2.
For example:
fibonacci(1)
đ¸ first condition is True so print '0'
>> 0
fibonacci(2)
đ¸ second condition True so print '0' and '1'
>> 0 1
fibonacci(5)
đ¸ both condition is False
đ¸ proceed to else block
đ¸ print 0, 1, 1 consecutively
đ¸ for x in range(n-3) will also become for x in range(2) since 5-3 is 2
đ¸ There will be two iterations to calculate for the next fibonacci numbers (sum of the current number and previous sum).
>> 0 1 1 3 5
đš 0 1 1 was manually printed and 3 5 are calculated inside the for loop
TIP: You can shorten this code if you replace the range(n-3) with range(n), and replacing the value of a to 0, thus making the two if elif conditions unnecessary, since you can make all the calculations inside the for loop for all numbers.
https://code.sololearn.com/cu51HvnrEbwg/?ref=app