Homework Solution

Dictionaries

Problems to be Submitted (18 points)

  1. (6 points)

    items = []
    for k in data:
        items.append( (k, data[k]) )
    
    or if you wish to use list comprehension syntax
    items = [ (k,data[k]) for k in data ]
    

  2. (6 points)

    Here is one possible approach...

    if 'CA' in captial:
        val = capital['CA']
    else:
        capital['CA'] = 'Springfield'
        val in 'Springfield'
    
    Here is another way to express the logic...
    if 'CA' not in capital:
        captial['CA'] = 'Springfield'
    val = capital['CA']
    

  3. (6 points)

    def pairSum(data, goal):
        # build dictionary of frequencies
        count = {}
        for val in data:
            count[val] = 1 + count.get(k, 0)
    
        # now look for goal
        for val in data:
            rest = goal-val
            # if rest == val, need to ensure two distinct occurrences within the data
            if rest in count and (rest != val or count[rest] >= 2):
                return True
        return False
    
    It is worth noting that this can be accomplished with a set rather than a dict so long as care is taken to ensure a single value cannot be used twice, unless it appears twice in the input.
    def pairSum(data, goal):
        prev = set()
        for val in data:
            if goal-val in prev:
                return True
            prev.add(val)      # save this for later use      
        return False
    


Extra Credit

  1. (2 points)


Last modified: Wednesday, 14 April 2010