Problem 1 ----------- [w for w in compounds if len(w) < 6] [5*x for x in range(5,820)] OR [x for x in range(1,4096) if x % 5 == 0] [x for x in range(2,10000) if prime(x)] Problem 2 ----------- def minDistance(points): md = distance(points[0],points[1]) for i,p in enumerate(points): for q in enumerate(points[i+1:]): d = distance(p,q) if d < md: md = d return md -- Alternatively, initialize md to 100000000000 (a large number) Problem 3 ---------- total = sum([data[1]*data[2] for data in stocks]) highPrice = max([d[1] for d in stocks]) biggies = [s[0] for s in stocks if s[1] > 500] Problem 4 --------- def removeBad(): global badLetters, possibleWords possibleWords = [ w for w in possibleWords if set(w) & badLetters == set() ] OR use len(badletters) == 0 OR badset = set() for w in possibleWords: for b in badLetters: if b in w: badset.add(w) possibleWords = list(set(possibleWords) - badset) OR copy = possibleWords[:] for word in copy: for letter in word: if letter in badLetters: possibleWords.remove(word) break ----- Problem 5 ---------- mean = float(sum(nums)) / len(nums) -- median = sorted(nums)[len(nums) / 2] OR nums.sort() middle = len(nums)/2 median = nums[middle] -- counts = {} for n in nums: counts[n] = counts.get(n, 0) + 1 mode = counts.keys()[counts.values().index(max(counts.values()))] OR moccurs = 0 mvalue = 0 for n in nums: if nums.count(n) > moccurs: moccurs = nums.count(n) mvalue = n mode = mvalue OR count = {} for n in nums: if n not in count: count[n] = 0 count[n] += 1 pairs = [(value,key) for (key,value) in count.items] pairs.sort() mode = pairs[-1][1] #last value has maximal occurrences, key is [1] Problem 6 ------------- def bbFan(filename): file = open(filename) counts = {} for line in file: data = line.split(',') for email in set(data[1:]) if email in counts: counts[email] += 1 else: counts[email] = 1 file.close() vals = sorted([ (x[1], x[0]) for x in counts.items() ]) return vals[-1][1] OR file = open(filename) counts = {} for line in file: data = line.split(',') song = data[0] for email in set(data[1:]) if email not in counts: counts[email] = [] counts[email].append(song) file.close() vals = sorted([ (len(x[1]), x[0]) for x in counts.items() ]) return vals[-1][1] OR, after file.close() most = 0 for id in counts: likes = counts[id] if len(likes) > most: most = len(likes) maxid = id return maxid