Having said that, it's common for professors to require algorithms that aren't naturally suited for recursion to be implemented recursively. It's also less efficient and less intuitive to write than an iterative implementation. If simplicity is required and memory overflow is not a major issue then use recursion otherwise go with iterations. If the length of the linked list is more than the call stack size, the class breaks for no reason. So, use either iteration or recursion according to the task you want to perform. Thus, recursion may cause memory overflow if your stack space is large, and is also inefficient in cases where the same value is calculated again and again. So even though recursion represented the algorithm in a natural way, it is very inefficient in this case. Similarly, fib(2) is calculated multiple times in this example. So, till this step, only fib(3) is calculated twice. And fib(4) leads to the calculation of fib(3) and fib(2). You can see that fib(5) leads to the calculation of fib(4) and fib(3). For example, let's calculate fib(5) with the above-given algorithm. But the major problem with this is that the same value will be calculated again and again for calculation of a Fibonacci term and this will take more time and more importantly, more stack space. However changing what it points to (via l newnode ) only changes what the pointer inside the function points to, it does not affect the one you passed as a parameter. Else it is f(n-1)+f(n-2) and the above code represents this in the most natural way. Having node l as a parameter means that your function has a local pointer variable that points to the same address as the pointer you pass in. This is the natural way of writing the Fibonacci series because according to the definition a Fibonacci number is 1 if 'n' is 0 or 1. If your intention is to add new nodes to the end of your linked list then you do not want to be resetting self.head each time a new node is added: def add (self, val): ''' Helper method for recursive add method ''' self.head self.recadd (val, self. Fib ( int n ) if ( n = 0 OR n = 1 ) return 1 else return fib ( n - 1 ) + fib ( n - 2 )
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |