Test 1 Solutions CompSci 6 Fall 2011 1. A 1. B. 22 o 22 os 2 try 3.33333333333 chickory True ['chickory', 'parsley'] 2A. def areaEquilateralTriangle(side): return (math.sqrt(3)/4.0) * (side**2) ALTERNATE SOLUTION: def areaEquilateralTriangle(side): return (3**(0.5)/4.0) * (side*side) 2B. def whoseNightToCook(day, month): if day %2 == 0: # even day return "Ellen" if day == 31 and month % 2 == 0: return "Ellen" return "Oscar" ALTERNATE SOLUTION: whoseNightToCook(day, month): if day%2 == 0 or (day == 31 and month %2 == 0): return "Ellen" else return "Oscar" 3. A1. [3, 5, 5, 7, 4] A2. 7 A3. ['chicken'] A4. 'chicken' B1. 'rhino' B2. Mystery returns the longest string. If there are multiple strings of that length, it returns the first such. B3. amount = max([len(w) for w in animals]) B4. Mystery still returns the longest string. If there are multiple strings of that length, now it returns the last such. 4.A.def getAges(data): answer = [] for w in data: splitLine = w.split(':') numberStr = splitLine[-1] answer.append(int(numberStr)) return answer ALTERNATE SOLUTION: def getAges(data): answer = [] # each string in data is replaced by a list of three strings for (index, value) in enumerate(data): data[index] = info.split(":") for info in data: # for each list in data answer.append(int(info[2])) return answer ALTERNATE SOLUTION: def getAges(data): return [int(w.split(':')[-1]) for w in data] ALTERNATE SOLUTION: def getAges(data): templist = [] for w in data: templist.append(data[(w.find(':')+1):]) ages = [] for v in ages: ages.append(int(templist[(v.find(':')+1):])) return ages ALTERNATE SOLUTION: (same as above but with list comprehensions) def getAges(data): templist = [data[(w.find(':')+1):] for w in data] ages = [int(templist[(v.find(':')+1):] for v in templist] return ages B. def howManyInRange(values, start, end): agelist = getAges(values) int count = 0 for age in agelist: if start <= age <= end: count += 1 return count ALTERNATE SOLUTION: def howManyInRange(values, start, end): agelist = getAges(values) ages = [] for age in agelist: if start <= age <= end: ages.append(age) return len(ages) ALTERNATE SOLUTION: def howManyInRange(values, start, end): values = getAges(values) return sum([1 for num in values if num >= start and num <= end]) ALTERNATE SOLUTION: def howManyInRange(values, start, end): return len([num for num in getAges(values) if num >= start and num <= end]) 5. def convertWord(word): if word.lower() == "hello": return "Ahoy" pos = word.find("ar") if (pos > 0): return word[:pos] + 'arrr' + word[pos+2:] if (len(word)> 7) and pos == -1: ans = "" for ch in word: if ch != 'o' and ch != 'u': ans += ch return ans return word ALTERNATE SOLUTION: def convertWord(word): if word == "hello" or word == 'Hello': return "Ahoy" if word.startsWith("ar") return word pos = word.find("ar") if (pos > 0): return word[:pos+2] + 'rr' + word[pos+2:] if (len(word)> 7): word = word.replace("o","") word = word.replace("u","") return word return word