What will this code print? Figure it out by hand, then run the code to confirm. Then slightly edit the code and try again.
- Trace #1:
def ct1(L):
a = dict()
for b in L:
if b[0] not in a:
a[b[0]] = set()
a[b[0]].add(b)
k = a.keys()
o = sorted(list(k))
print(len(k))
print(o)
print(a[o[-1]])
m = ["surround", "friend", "stop", "plane", "glossy", "bouncy", "puncture", "mate", "plant", "chin", "powerful", "cars"]
ct1(m)
- Trace #2:
def ct2(L):
d = dict()
for i in range(len(L)):
d[sum(L[i:])] = L[i]
print("1:",d)
for item in L:
if item in d:
d[item] += 1
print("2:",d)
b = copy.deepcopy(d)
for k in b:
if d[k] % 2 == 1:
del d[k]
return d
print("3:",ct2([1,2,3,4]))
- Trace #3:
def ct3(s):
d = {}
for i in range(len(s)):
d[s[i]] = i
for c in d:
print (d[c])
for c in s:
d[c] = d[c] + 1
for c in d:
print (d[c])
return s
ct3("borrow")
- Trace #4:
d = {1:"one","v":"quiz4"}
a = range(3)
for i in a:
print (d.get(i,"v"))
- Trace #5:
def ct5(lst):
d1 = dict()
for i in range(len(lst)):
if lst[i] not in d1:
d1[lst[i]] = 0
d1[lst[i]] += 1
print(d1)
d2 = dict()
for key in d1:
d2[d1[key]] = key
print(d2)
for key in d2:
d1[key] = d2[key]*2
for key in d1:
print("key:", key, "value:", d1[key])
return d1.get(4, 1)
lst = [1, 5, 1, 1, 2, 5]
print(ct(lst))
- Fill in the blanks
Consider the following function. Fill in a single line of code to complete it. (If you can’t do it in one line,
you can use more than one line for, at most, half credit.)
# Return a dictionary mapping words in L to the number of times they occur in L
# For example, wordCounter(["a","b","b","c","a","monkey"]) returns # {'a': 2, 'b': 2, 'c': 1, 'monkey': 1}
def wordCounter(L):
d = {}
for word in L:
______________________________________________________
return d
- cheapestProducts(priceList)
Write the function cheapestProducts(priceList) which, given a list of tuples each containing the product name, store
name, and price of a product, returns a dictionary mapping product names to a tuple containing the store and price
for the lowest price found for the item. In the event of a tie, either store may be used. Consider the following
example :
productList = [ ("X-Box", "LuLu", 1200), ("iPhone XR", "Carrefour", 3000), ("Washer", "SafariMart" , 799), ("iPhone XR", "Al Anees" , 2870), ("Washer", "LuLu", 899) ]
cheapestProducts(priceList)
returns a dictionary containing...
{'X-Box': (1200, 'LuLu'), 'iPhone XR': (2870, 'Al Anees'), 'Washer': (799, 'SafariMart')}
- commonKeysDictionary(L)
Write the function commonKeysDictionary(L) that takes a list of dictionaries and combines them into a single dictionary.
The combined dictionary should contain only keys that are present in all the dictionaries in L. The value of each key in
the combined dictionary should be the set of values associated with that key from the dictionaries in L. For example given:
L = [ {"a": 1, "b": 2}, {"a": 3, "c": 4}, {"a": 5} ]
commonKeysDictionary(L)
returns {"a": {1,3,5}}, because the only key that is present in all the three dictionaries in L is a.
More examples:
L = [{"a": 1, "b": 2, "c":42}, {"a": 1, "c": 4}]
assert( commonKeysDictionary(L) == {"a": {1}, "c": {4,42}})
L = [{"a": 1, "b": 2},{"a": 3, "c": 4},{"a": 5}]
assert( commonKeysDictionary(L) == {"a": {1,3,5}})
L=[]
assert( commonKeysDictionary(L) == dict())
- mostVisits(logbook)
Most Frequent Visitor Write the function mostVisits(logbook) that is given a dictionary mapping days of the week to the
list of students who visited CMU-Q on that day, and returns a set that contains the student (or students, if there
is a tie) who visited on the most number of days that week. There is one caveat: The log system might register
a visit multiple times on the same day, therefore one name might appear multiple times in a list, but it should be
counted only once per day. For example, given the dictionary:
{ "Sunday" : [ "Layla", "Peter", "Otto", "Amir" ],
"Monday" : [ "Yusuf", "Layla", "Bernard", "John" ],
"Tuesday" : [ "Yusuf", "Peter", "Otto", "Layla", "Salma", "Otto" ],
"Wednesday" : [ "Otto", "Layla", "Yusuf", "Otto" ] }
The function should return the set {"Layla"}, since Layla visited the CMU-Q building four days
(Otto entered the building more times, but only visited on three different days). If Layla had not visited the
building on Monday, then it would return {"Layla", "Otto", "Yusuf"}, since each student would have visited exactly three days.
- dictDifference(d1, d2)
Write the function dictDifference(d1, d2) that takes two dictionaries whose values are sets and returns a new dictionary
that results from taking d1 and removing the values in d2 for the common keys. If one the values becomes an empty set in
the resulting dictionary, then the key should be removed. The values of non-common keys should remain the same. The
function should be non-destructive. For instance,
dictDifference({'cmu':{1,2,3}, '112':{4,5}}, {'112':{5}}) should return {'cmu': {1, 2, 3}, '112': {4}}
because the only common key is '112' and when we remove the values d2['112'] from d1['112']
we get the set {4}.
dictDifference({'cmu':{1,2,3}, '112':{4,5}}, {'112':{4,5,6}}) should return {'cmu': {1, 2, 3}} because
the only common key is '112' and when we remove the values d2['112'] from d1['112'] we get an empty set
and we must remove the key '112'.
Finally, dictDifference({'cmu':{1,2,3}, '112':{4,5}},{ 'cmu': {3,4,5}, '112':{6,7,8}}) should return {'cmu': {1, 2}, '112': {4, 5}}
because when we remove the values d2['cmu'] from d1['cmu'] we get {1,2} (only 3 is common to both sets),
and when we remove values d2['112'] from d1['112'] nothing changes (the sets are disjoint).
- findFlukeNumbers(L)
A fluke number (coined term) is an integer that has a frequency in the list equal to its value Write the function
findFlukeNumbers(L)) that is given a list L of objects (not necessarily integers). The function should return a set
containing all the fluke numbers in the list. For example,
assert(findFlukeNumbers([1,'a','a',[4], 3, False, 3, 3]) == {1, 3})
assert(findFlukeNumbers([1, 2, 2, 3, 3, 3, 4]) == {1, 2, 3})
assert(findFlukeNumbers([0, False, 'hello']) == set())