Is there something wrong with this python code, why does it run so slow compared to ruby?

后端 未结 5 794
孤城傲影
孤城傲影 2021-01-13 07:54

I was interested in comparing ruby speed vs python so I took the simplest recursive calculation, namely print the fibonacci sequance.

This is the python code

5条回答
  •  春和景丽
    2021-01-13 08:26

    Your method of calculating the first 35 numbers in the fibonacci sequence is immensely inefficient. You run a function fib() 35 times, and each time fib() has exponential run time. The generator in Python is the perfect solution to this problem and is far more efficient than what you wrote in Ruby.

    def fibo_generator(n):
        # gets Fibonacci numbers up to nth number using a generator
        a, b = 0, 1
        for _ in range(n):
            yield a
            a, b = b, a + b
    

    You can then print all fibonacci numbers up to 35 using this code:

    for f in fibo_generator(35):
        print f
    

    This is by far the most efficient way to implement the fibonacci sequence in Python as well as the most versatile.

提交回复
热议问题