What I wrote last
is how to solve problems about recursive function. In this week, I will write some exercises
about recursive function.
count_elements(‘snork’)
count_elements([2,
1, 3])
The answer for the
first one is 1, because ‘snork’ is not a list.
For the second one, the answer is 1.
Since [2, 1, 3] is a list, the function will run sum([count_elements(x)
for x in L]) and will return sum([1 ,1, 1]) which is 3.
nd(‘ox’)
nd([])
The answer for the
first one is 0, because ‘ox’ is not a list. For the second one, since [] is a list though
it is an empty list, the function will run 1 + max([nd(x) for x in (L+ [‘ox'])])
and L will become ['ox']. Since 'ox' is not a list, which will let L become [0]. Then the function will return 1 eventually.
After doing these exercises, solving recursive function becomes much easier.


没有评论:
发表评论