Help for Fibonacci in Python | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Help for Fibonacci in Python

"The Fibonacci sequence is one of the most famous formulas in mathematics. Each number in the sequence is the sum of the two numbers that precede it. For example, here is the Fibonacci sequence for 10 numbers, starting from 0: 0,1,1,2,3,5,8,13,21,34. Write a program to take N (variable num in code template) positive numbers as input, and recursively calculate and output the first N numbers of the Fibonacci sequence (starting from 0). Sample Input 6 Sample Output 0 1 1 2 3 5" #my code num = int(input()) def fibonacci(n): #complete the recursive function if n<=1 : return n else : a = 0 b = 1 print(a) print(b) print(end='') for i in range (2, n): c = a+b print (c) print (end='') a = b b = c print (fibonacci (num)) #my output for n = 6 0 1 1 2 3 5 none <<< why none is printed ?

19th Dec 2022, 12:08 PM
Ben Hamida Mohamed Amine
Ben Hamida Mohamed Amine - avatar
1 ответ
+ 3
You could use a loop and 2 variables Start with a = 1 b = 1 On the next iteration fib = a + b # (the latest fib number) Update a and b: a = b # (a is now b, one number before the latest number) b = fib # (the latest number) And so on.
19th Dec 2022, 12:58 PM
Lisa
Lisa - avatar