0

Comparing Fibonacci codes: cleaner code, yet slower

I'm teaching myself Python and I wrote my own (inelegant) code for the Fibonacci sequence: def fibonacci(n): count = 0 a = 1 b = 0 while count <n: count += 1 c = a + b yield c if count%2 == 1: b = c continue if count%2 == 0: a = c continue for c in fibonacci(40): print(c) It works, but I felt it was a bit bulky, so I looked to see how other people did it and found this much shorter one: def Fibonacci(n): if n<0: print("Incorrect input") elif n==1: return 0 elif n==2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) print(Fibonacci(40)) The second one is much shorter. Yet, if you run them both, mine prints every number in the sequence in a fraction of a second, while the second takes about a minute to print one value (and the discrepancy only gets worse as n increases for both). Why is there such a difference in the times?

8th Apr 2020, 2:30 PM
Savager
1 Resposta
+ 1
the second one uses recursion that's why it is slower. recursion is slower than looping.(at least in python)
8th Apr 2020, 3:23 PM
Bahhaⵣ
Bahhaⵣ - avatar