CS 111 Lecture: Use It Or Lose It Recursion

Table of Content

  1. Sublists
  2. The sublistSum function
  3. Alternative approach to sublistSum
  4. Exercise 1: sublists

1. Sublists

For a given list L (possibly containing duplicates), we will use the term sublist of L to refer to any list that keeps some elements of L and omits others in their same relative order. E.g., the sublists of [5, 3, 8, 3] are:

[5, 3, 8, 3] # Keep all elements
[3, 8, 3] # Omit 5
[5, 8, 3] # Omit 1st 3
[5, 3, 3] # Omit 8
[5, 3, 8] # Omit 2nd 3
[8, 3] # Omit 5 and 1st 3
[3, 3] # Omit 5 and 8
[3, 8] # Omit 5 and 2nd 3
[5, 3] # Omit 8 and 1st 3
[5, 3] # Omit 8 and 2nd 3  # (Note duplication)
[5, 8] # Omit both 3s
[5] # Keep only 5
[3] # Keep only 1st 3
[8] # Keep only 8
[3] # Keep only 2nd 3      # (Note duplication)
[] # Omit all elements

In the following we will look at a few different examples using sublists. You will also write your own function to create all sublists of a list, recursively.

2. The sublistSum function

Given a list of numbers (possibly containing duplicates) and a target number, sublistSum returns a list of all sublists whose sum is the target number. For example:

sublistSum([2, 3, 5, 5, 11, 17], 23) --> [[2, 5, 5, 11]]  
sublistSum([2, 3, 5, 5, 11, 17], 30) --> [[2, 11, 17], [3, 5, 5, 17]] 
sublistSum([2, 3, 5, 5, 11, 17], 24) --> [[2, 5, 17], [2, 5, 17], [3, 5, 5, 11]] 
sublistSum([2, 3, 5, 5, 11, 17], 34) --> [] 

Note: More details about these results and how sublistSum works are given in the lecture slides.

In [1]:
def sublistSum(nums, target):
    '''Assume nums is a list of numbers. Return a list of all sublists of nums
       whose numbers sum to target. If nums contains duplicates, 
       there might be duplicate sublists in the result.
       This implementation does not use sublists (see below) as a helper function,
       and instead does a recursion directly. 
    '''
    if nums == []: # base case
        # Subtlety: there are *two* sub base cases: 
        if target == 0:
            return [[]] # sum([]) == 0, so include [] in result list
        else:
            return [] # sum([]) cannot be a nonzero target,
                      # so don't include [] in result
    else: 
        fst = nums[0] # first number in list
        rst = nums[1:] # rest of numbers in list
        usingFirst = [([fst] + sumList) # all sublists USING (keeping) fst 
                        for sumList in sublistSum(rst, target-fst) 
                                       # recursive call excludes fst
                       ]
        losingFirst = sublistSum(rst, target) # all sublsts LOSING (omitting) fst
        return usingFirst + losingFirst

To test the function, we will write a helper function:

In [2]:
def testSublistSum(nums, target):
    '''Helper function to test the function sublist'''
    print(f'sublistSum({nums}, {target}) => {sublistSum(nums,target)}')

Now we can call the testSublistSum many times to test sublistSum:

In [24]:
for tgt in range(19,36):
    testSublistSum([2, 3, 5, 10, 10, 17], tgt)
sublistSum([2, 3, 5, 10, 10, 17], 19) => [[2, 17]]
sublistSum([2, 3, 5, 10, 10, 17], 20) => [[2, 3, 5, 10], [2, 3, 5, 10], [3, 17], [10, 10]]
sublistSum([2, 3, 5, 10, 10, 17], 21) => []
sublistSum([2, 3, 5, 10, 10, 17], 22) => [[2, 3, 17], [2, 10, 10], [5, 17]]
sublistSum([2, 3, 5, 10, 10, 17], 23) => [[3, 10, 10]]
sublistSum([2, 3, 5, 10, 10, 17], 24) => [[2, 5, 17]]
sublistSum([2, 3, 5, 10, 10, 17], 25) => [[2, 3, 10, 10], [3, 5, 17], [5, 10, 10]]
sublistSum([2, 3, 5, 10, 10, 17], 26) => []
sublistSum([2, 3, 5, 10, 10, 17], 27) => [[2, 3, 5, 17], [2, 5, 10, 10], [10, 17], [10, 17]]
sublistSum([2, 3, 5, 10, 10, 17], 28) => [[3, 5, 10, 10]]
sublistSum([2, 3, 5, 10, 10, 17], 29) => [[2, 10, 17], [2, 10, 17]]
sublistSum([2, 3, 5, 10, 10, 17], 30) => [[2, 3, 5, 10, 10], [3, 10, 17], [3, 10, 17]]
sublistSum([2, 3, 5, 10, 10, 17], 31) => []
sublistSum([2, 3, 5, 10, 10, 17], 32) => [[2, 3, 10, 17], [2, 3, 10, 17], [5, 10, 17], [5, 10, 17]]
sublistSum([2, 3, 5, 10, 10, 17], 33) => []
sublistSum([2, 3, 5, 10, 10, 17], 34) => [[2, 5, 10, 17], [2, 5, 10, 17]]
sublistSum([2, 3, 5, 10, 10, 17], 35) => [[3, 5, 10, 17], [3, 5, 10, 17]]

3. Alternative approach to sublistSum

Suppose we had a sublists function that returns all sublists of a list. E.g.:

sublists([5, 3, 5, 8]) 
-->  [[5, 3, 5, 8], [5, 3, 5], [5, 3, 8], [5, 3], 
      [5, 5, 8], [5, 5], [5, 8], [5], 
      [3, 5, 8], [3, 5], [3, 8], [3], 
      [5, 8], [5], [8], []]

Then we could define sublistSum as:

def sublistSum(nums, target):
    """Alternative implemenation of sublistSum using the recursive
    function sublists and list comprehension.
    """
    return [ns for ns in sublists(nums) if sum(ns) == target]

In the next exercise, you'll help complete the definition of sublists and then test this new solutions for sublistSum.

4. Exercise 1: sublists

You are given the almost complete body of the function sublists. Your task is to fill in the skeleton of the function that is provided in slide 11 of today's lecture.

In [26]:
def sublists(vals):
    '''Given a list of n values (which might contain duplicates),
       return a list of all possible 2^n sublists, where a sublist is the 
       result of independently choosing to keep (use) or not keep (lose)
       particular value occurrences without changing their relative order. 
       The order of sublists is not specified. 
       E.g., one ordering of the sublists of [3,1,2] is 
       [ [], [2], [1], [1, 2], [3], [3, 2], [3, 1], [3, 1, 2] ]
       When the given lists contains duplicates, there will be duplicate
       sublists. e.g. one ordering of the sublists of  [1, 3, 1, 2] is 
       [[], [2], [1], [1, 2], [3], [3, 2], [3, 1], [3, 1, 2], 
       [1], [1, 2], [1, 1], [1, 1, 2], [1, 3], [1, 3, 2], [1, 3, 1], [1, 3, 1, 2]]
       in which the sublists [1, 2] and [1] each appear twice. 
    '''
    # Your code here
    if vals == []: 
        return [[]]
    else:
        fst = vals[0]
        rst = vals[1:]
        losingFirst = sublists(rst) # all sublsts LOSING (omitting) fst
        usingFirst = [[fst] + sublist for sublist in losingFirst] # all sublsts USING (keeping) fst
        return usingFirst + losingFirst

Let's define a helper function to test sublists and use it for several test cases:

In [14]:
def testSublists(vals):
    '''Helper function to test the function sublist'''
    print(f'sublists({vals}) => {sublists(vals)}')

for lst in [[], [5], [4,5], [3,4,5], [2,3,4,5], [1,2,3,4,5]]:
    testSublists(lst)
sublists([]) => [[]]
sublists([5]) => [[5], []]
sublists([4, 5]) => [[4, 5], [4], [5], []]
sublists([3, 4, 5]) => [[3, 4, 5], [3, 4], [3, 5], [3], [4, 5], [4], [5], []]
sublists([2, 3, 4, 5]) => [[2, 3, 4, 5], [2, 3, 4], [2, 3, 5], [2, 3], [2, 4, 5], [2, 4], [2, 5], [2], [3, 4, 5], [3, 4], [3, 5], [3], [4, 5], [4], [5], []]
sublists([1, 2, 3, 4, 5]) => [[1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 3], [1, 2, 4, 5], [1, 2, 4], [1, 2, 5], [1, 2], [1, 3, 4, 5], [1, 3, 4], [1, 3, 5], [1, 3], [1, 4, 5], [1, 4], [1, 5], [1], [2, 3, 4, 5], [2, 3, 4], [2, 3, 5], [2, 3], [2, 4, 5], [2, 4], [2, 5], [2], [3, 4, 5], [3, 4], [3, 5], [3], [4, 5], [4], [5], []]

We can now test the alternative sublistSum as well, but first let's put here its definition and a testing helper function.

In [25]:
def sublistSumAlt(nums, target):
    """Alternative implemenation of sublistSum using the recursive
    function sublists and list comprehension.
    """
    return [ns for ns in sublists(nums) if sum(ns) == target]

def testSublistSumAlt(nums, target):
    '''Helper function to test the function sublistSumAlt'''
    print(f'sublistSumAlt({nums}, {target}) => {sublistSumAlt(nums,target)}')

for tgt in range(19,36):
    testSublistSumAlt([2, 3, 5, 5, 11, 17], tgt)
sublistSumAlt([2, 3, 5, 5, 11, 17], 19) => [[2, 17], [3, 5, 11], [3, 5, 11]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 20) => [[3, 17]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 21) => [[2, 3, 5, 11], [2, 3, 5, 11], [5, 5, 11]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 22) => [[2, 3, 17], [5, 17], [5, 17]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 23) => [[2, 5, 5, 11]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 24) => [[2, 5, 17], [2, 5, 17], [3, 5, 5, 11]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 25) => [[3, 5, 17], [3, 5, 17]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 26) => [[2, 3, 5, 5, 11]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 27) => [[2, 3, 5, 17], [2, 3, 5, 17], [5, 5, 17]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 28) => [[11, 17]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 29) => [[2, 5, 5, 17]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 30) => [[2, 11, 17], [3, 5, 5, 17]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 31) => [[3, 11, 17]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 32) => [[2, 3, 5, 5, 17]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 33) => [[2, 3, 11, 17], [5, 11, 17], [5, 11, 17]]
sublistSumAlt([2, 3, 5, 5, 11, 17], 34) => []
sublistSumAlt([2, 3, 5, 5, 11, 17], 35) => [[2, 5, 11, 17], [2, 5, 11, 17]]

This is the end of this notebook!