Recursive functions
When I first learned about recursion it was explained as follows:
- A recursive function must call itself.
- There must be a possible "end" of a recursion, this way the recursion can start working "backwards" and return values.
- There must be a base case, so that the recursion may end.
This procedure can be demonstrated using a Python function:
return 1 + max([nested_depth(x) for x in L] + [0]) if isinstance(L, list) else 0
The base case is covered if there is no list, the function simply returns 0. The end of the recursion is the last list(the point when the function starts returning values). The recursive call is inside the list comprehension, and it is only called when the Ternary operator evaluates to True.
The simplest form of recursion, I believe, is a nested array: [1, [0,1]]
Suppose I wanted to sum the above array, well once we get to the second element, the type becomes a list, it is also not unreasonable to assume this breaks whatever function we have because we didn't account for a list type.
A simple solution to this problem is to simple check if the element being performed is a list, then we simple call the function again, this way we can think of the procedure being as follows:
Foo([1])
Foo([0, 1])
Now it should be clear how useful recursion is.
Trees & Children
Suppose we have a standard Tree and suppose this Tree has four Children. Let us say the values of the nodes are 1, 5, 7, and 9.
There can only be many different configurations with this Tree. One possible configuration is as follows:
1 is a Root, the Children are 5 and 7, and 9 can be the child of either 5 or 7.
1 is a Root, the Child is 5, the Child of 5 is 7, and the Child of 7 is 9.
The idea behind a Tree is recursive! This is because when we want to reach a certain node, we must call recursion continuously until we reach that node, then we can return that node, or work backwards and return all the Parents of that Node.
Trees are an essential part of computer infrastructure, because they are used to store information in an organized and efficient way.
The following Tree in python uses the first element, 5, to associate itself with a data structure. Perhaps the 5 is used by other Trees. Regardless, the idea that we can associates 5 with information is essential to organization.
The following example does not have to make sense, just note the use of the Tree structure. Perhaps 5 is a client ID for a person who works for a bank, or a person who invests in a bank:
[5, ['bank_income', ['5000'], ['growth_rate',[1],[5]] ] ]
No comments:
Post a Comment