This week, we learned more about recursion.
The recursion technique carries out a job very much like the effect that a while loop does. A while loop, as covered in csc108, is a condition that is not met so that the sequence of code executes itself over and over again until either the condition is met or your computer run out of memory and crashes. The while loop learned and implemented in csc108 was a powerful tool in that it executes a large sequence of code repeatedly until the job is done. However, the implementation of the while loop has its flaws. Usually, the biggest problem a developer encounters during the implementation of a while loop is trying to determine, "will it run forever?" or "will it eventually stop?" Using a while loop, that is well-defined within its "while: ...." statement. Otherwise, if the while loop just keeps running and running, the code will crash and you could lose data.
The recursion technique, simply put, is given a base case, call the function within it self again and again until the base case is met. Recursion aims to solve problems where there are nested lists - lists within a list.
For example there is a list [0, 1, 2, [3[4,5,6]], 7], and you want to be able to iterate through every single element within every list, a while loop is not nearly as convenient as implementing recursion.
def rec_max(L):
return max([rec_max(x) if isinstance(x, list) else x for x in L])
the function rec_max is called within the function itself and else is defined as the base case.
a seemingly intimidating technique, but definitely among the most powerful we will encounter in this course.
This comment has been removed by the author.
ReplyDeleteI like your connection between recursion and while loops but I also think of recursion as being a worthwhile alternative to any iterative code. Yet under what circumstances is recursion actually more efficient than the iterative alternative? I generally think that it is only for complex problems like the one that you described. For simple problems though, I think recursion is overkill.
Delete