F. len(L): returns the number of objects in mylist.

From EECS 182
F. len(L): returns the number of objects in mylist.
Jump to: navigation, search
  1. best to solve recursively because the answer is trivial if the mylist object is empty and mylist is a recursive structure (a mylist object consists of mylist.pop() + mylist.last()).
  1. Base case: L is empty. Then, the answer is 0
  2. Non-base case: Decompose L into L.pop() and L.last(). L.pop() is now a smaller list. Assume that len works on that (recursive step). Can we construct the answer if we knew len(L.pop())? The answer is yes. We simply have to add 1 to it to get the answer. So, the answer will be len(L.pop()) + 1.

def len(L):

   if (L.isempty()):
       return 0
   else:
       return len(L.pop()) + 1
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
EECS @ UM
Tools