This week we talked about binary tree in
class. The recursion we saw before were all in the style of:
if: ……
else: ……,
but in the code of bst_contains_vl(node, v), we saw recursion in: if: ……
elif: ……
elif:
……
else: ……
Recursion
means a function calls itself to solve problems. It’s really convenient to use
recursion in some situation. For example, count the element of a list. People
might say ”Oh, this is easy, we can choose a counter n, then for every element
in the list n = n + 1. We can do it without recursion. ” This is doable when
the list is very simple like this: [1, 2, 3, 4, 5]. But what if the list look
like this: [1,[2,[3,[4, 5]]]]? Then it’s very difficult to solve this problem
in a traditional way. This is why we use recursion. If we use recursion, the
function itself will look for the numbers in the list:
if not isinstance(L,
list):
return 1
else:
return sum([count_element(c) for c in L])
You
may think you get the idea of recursion after some practice, but you will know
you are wrong when you see this:
def M(n):
if n > 100:
return n – 10
else:
return f(f(n + 11))
It’s called McCrathy 91 function. The
results of evaluating the function are given by M(n) = 91 for
all integer arguments n ≤ 100, and M(n) = n − 10
for n > 100. Indeed, the result of M(101) is also 91 (101 - 10 =
91). All results of M(n) after n = 101 are continually increasing by 1, e.g.
M(102) = 92, M(103) = 93. I try to trace this function, but the process is
really hard.
Recursion
can be very challenging, the only way to understand a recursive function is to
trace it.
没有评论:
发表评论