CompSci 101 Sec 02, Fall 2014, Exam 2 Solutions Problem 1 ['fa', 'me', 're', 'so'] ['la', 'me', 're', 'do'] set([8, 6]) set([2, 4, 6, 8, 10, 13]) set([2, 4, 10, 13]) Y ['Duke', 'ECU', 'UNC', 'WFU'] set(['Y', 'P', 'B']) ['B', 'G', 'Y'] WFU OR UNC Problem 2 A. [15, 9, 3] [5, 8] 5 B. containsA = [x for x in words if 'a' in x or 'A' in x] OR containsA = [x for x in words if 'a' in x.lower()] OR containsA = [x for x in words if x.count('a')>0 or x.count('A')>0] C. firstThree = [item[0:3] for item in words if len(item) > 5] OR firstThree = [item[:3] for item in words if len(item) > 5] Problem 3 A. def fileToList(fileMeals): answer = [] for line in fileMeals: line = line.strip() answer.append(line.split(":")) return answer OR return [line.strip().split(":") for line in fileMeals] B. def foodEaten(data, name): food = [] for item in data: fullname = item[2].split(" ") if fullname[-1] == name: food.append(item[0]) return food OR def foodEaten(data, name): return [item[0] for item in data if item[2].split()[-1] == name] Problem 4 A. def listOfSchools(data): setSchools = set([]) for item in data: setSchools.add(item[0]) alist = list(setSchools) alist.sort() return alist OR def listOfSchools(data): listSchools = [] for item in data: listSchools.append(item[0]) alist = list(set(listSchools)) alist.sort() return alist OR def listOfSchools(data): listSchools = [] for item in data: if item[0] not in listSchools: listSchools.append(item[0]) return sorted(listSchools) OR def listOfSchools(data): return sorted(list(set([item[0] for item in data]))) B. def problemsSolved(data): problems = set([]) for item in data: if item[3] == "correct": problems.add(item[1]) return list(problems) OR def problemsSolved(data): solved = [] for item in data: if item[3] == "correct" and item[1] not in solved: solved.append(item[1]) return solved C. def problemsNotSolved(problems, data): solved = problemsSolved(data) setProbs = set(problems) setSolved = set(solved) setNotSolved = setProbs.difference(setSolved) return list(setNotSolved) OR def problemsNotSolved(problems, data): notSolved = [] solved = problemsSolved(data) for pr in problems: if pr not in solved: notSolved.append(pr) return notSolved D. def dictSchoolToSolvedProblems(data): d = {} for item in data: if item[3] == 'correct': if item[0] in d: d[item[0]].append(item[1]) else: d[item[0]] = [item[1]] return d E. def dictSchoolToScore(data): schools = listOfSchools(data) d = {} for school in schools: d[school] = totalScoreSchool(data, school) return d F. def winner(data): d = dictSchoolToScore(data) win = ("", 0) for (key,value) in d.items(): if value > win[1]: win = (key,value) return win OR def winner(data): d = dictSchoolToScore(data) maxScore = max([d[key] for key in d]) for (key,value) in d.items(): if value == maxScore # found it return (key,value) return ("",0) # It should match something, but just in case