D. concat(L1, L2): returns a mylist that is a concatenation of L1 and L2.

From EECS 182
D. concat(L1, L2): returns a mylist that is a concatenation of L1 and L2.
Jump to: navigation, search

Returns the concatenation of two lists. Best to solve recursively. Why? Because the answer is easy to compute if one of the lists is empty (it will be the other list.). Given that it is easier to stick elements at the end using the append method, let's first try recursing on L2.

Solution:

def concat(L1, L2):
   if (L2.isempty()):
       return L1
   else:
       return concat(L1, L2.pop()).append(L2.last())

Other solutions:

def concat(L1, L2):
   if (L2.isempty()):
       return L1
   else:
       L2part = L2.pop()
       L1withL2part = concat(L1, L2part)   # put together L1 and L2part. Recursive step. Just assume it works.
       result = L1withL2part.append(L2.last())
       return result
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
EECS @ UM
Tools