Recursive Fibonacci sequence calculator (Python code coach challenge) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Recursive Fibonacci sequence calculator (Python code coach challenge)

Good afternoon to my fellow Sololearners. Has anyone found a purely recursive solution to the Python code coach challenge asking that we code a recursive algorithm to calculate and print the first n terms of the Fibonacci sequence? I calculated the correct result and passed the challenge with the code below, but my algorithm is not fully recursive. (I used a hybrid approach, calculating each term of the sequence recursively but the sequence as a whole iteratively.) https://code.sololearn.com/crL9N3nIRSz0/?ref=app

27th Nov 2020, 7:53 PM
Charles Hill
Charles Hill - avatar
7 Answers
+ 2
Thanks, Rik - great solution. What I was doing wrong was having the recursive function call itself twice - for n-1 and n-2 - which caused my code to calculate an incorrect Fibonacci sequence with duplicative elements.
27th Nov 2020, 9:47 PM
Charles Hill
Charles Hill - avatar
+ 1
I thought that I needed to design the recursive function to call itself only once, but I wasn’t able to come up with your very elegant and intuitive solution. Thanks again for answering and sharing your code.
27th Nov 2020, 9:50 PM
Charles Hill
Charles Hill - avatar
+ 1
27th Nov 2020, 10:00 PM
Rik Wittkopp
Rik Wittkopp - avatar
0
I sent you a DM with my solution
27th Nov 2020, 9:33 PM
Rik Wittkopp
Rik Wittkopp - avatar
0
Rik Wittkopp , Charles Hill Why did you guys only DM, why didn’t you share the solution? This below almost works — i get the desired output, but i also get an annoying “None” as an additional output in the end. And i don’t know how to make it go away. So my output is: 0 1 1 2 3 None And my code is: num = int(input()) def fibonacci(n): #complete the recursive function fibolist0 = [0, 1] for i in range(n): if i>=2: fibolist0.append(fibolist0[i-2] + fibolist0[i-1]) for el in fibolist0: print(el) print(fibonacci(num))
21st Feb 2021, 1:41 PM
Christos Nikolis
Christos Nikolis - avatar
0
Christos Nikolis I didn't share it publicly as it was a code coach challenge and I did not wish to post such answers publicly. I will look at yours now
21st Feb 2021, 6:14 PM
Rik Wittkopp
Rik Wittkopp - avatar
0
Hi Christos Nikolis Inside your def, you have print(el) but when you call your function, you use print again. This is causing your none error. Also your def is not using recursion, but a for loop to solve the challenge. I will try to DM you something which may help, but I suggest you review recursion again
21st Feb 2021, 6:30 PM
Rik Wittkopp
Rik Wittkopp - avatar