![]() Since your problem is that you re-compute values you have already computed, you can instead choose to save the values you have already computed in a dict, and try to get them from that before you recompute them. ![]() Memoization (relatively advanced technique)Īnother alternative to make it faster exists, but it is a little more complicated as well. Or you can get the 17th fibonacci number from a list of the first 40 by doing > fib_to(40)Ģ. Then you can get the first 20 fibonacci numbers by doing > fib_to(20) This approach would look something like this: > def fib_to(n): If you have a list of the fibonacci numbers, you can use the last two numbers in that list to create the next number. If you do that, you build "from the bottom up" or so to speak, and you can reuse previous numbers to create the next one. The easiest way is to just create a list of fibonacci numbers up to the number you want. ![]() There are a few options to make this faster: What makes it even worse is that with each fibonacci number you calculate in your list, you don't use the previous numbers you have knowledge of to speed up the computation – you compute each number "from scratch." That just gets worse and worse the higher the number you want to compute. As you can see, it computes the value of Fibonacci(2) three times, and the value of Fibonacci(1) five times. It represents calculating Fibonacci(5) with your function. The reason for this is that for each number calculated, it needs to calculate all the previous numbers more than once. The primitive recursive solution takes a lot of time.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |