Lecture 47:

posted May 1, 2013, 6:14 AM by Samuel Konstantinovich   [ updated May 1, 2013, 6:19 AM ]
Pick a partner. Everyone should have one partner, if there are an odd number of people in the class then there can be ONE group of three.  

You are responsible for your partner's actions today. If one of you doesn't do what you are supposed to do, my wrath will fall upon both of you. :)

Show a trace through each of these functions on paper (sorry no tablets/laptops this time). Determine which of them correctly inverts the dictionary. If not, explain what happens. Do not run idle to check your answers, instead: compare your answers with another pair of students.

Here is a sample dictionary and the results: (remember order doesn't matter)
 { 'a':99 , 'b':34,  'c':99, 'd':100, 'e':34 }  --> {34: ['b', 'e'], 99: ['a', 'c'], 100: ['d']}

def invert(D):
    newD = {}
    for key in D:
        newD[D[key]]=[key]
    return newD

def invert(D):
    newValues = D.keys()
    newKeys = D.values()
    newD = {}
    for i in range(len(newValues)):
        if newKeys[i] in newD:
            newD[newKeys[i]].append(newValues[i])
        else:
            newD[newKeys[i]]= [ newValues[i] ]
    return newD

def invert(D):
    q = {}
    for h in D:
        q[D[h]]=[h]
    for h in D:
        q[D[h]].append(h)
    return q

def invert(D):
    z = {}
    for x in D:
        if D[x] in z:
            z[D[x]].append(x)
        else:
            z[D[x]]= [ x ]
    return z

def invert(D):
    newD = {}
    for key in D:
        newD[D[key]]=[]
    for key in D:
        newD[D[key]].append(key)
    return newD


def invert(D):
    newD = {}
    for key in D:
        newKey = D[key]
        newVal = key
        if newKey in newD:
            newD[newKey].append(newVal)
        else:
            newD[newKey]= [ newVal ]
    return newD  



Comments