Test 1, Compsci 6, Fall 2010 --------------- Problem 1 --- num = 13 d = 7.5 s = "please" print num/2 = 6, integer division truncates in Python 2.6 (changes in 3.0) print s[1:] = "lease" print s[3] = 'a' (index starts at 0) print num % 5 = 3, % is remainder, 13 = 2*5 + 3 print s*2 = "pleaseplease" print (num-11)**3 = 8 since 13-11 = 2 and 2*2*2 = 8 Problem 2 ---- def sphereV(r): return 4.0/3*math.pi*(r**3) def pyramid(levels): for n in range(1,levels+1): print '*' * n def pyramid(levels): for n in range(1,levels+1): for i in range(0,n): print '*', print def lastFirst(name): w = name.split(",") return w[1][1:] + " " + w[0] # alternative index = name.find(",") return name[index+2:] + " " + name[:index] def isPrime(n): for div in range(2,n): if n % div == 0: return False return True # alternative for loop for div in range(2,int(math.sqrt(n))+2): def domainCount(addrs,suffix): count = 0 for email in addrs: if email.endswith(suffix): count += 1 return count def domainCount(addrs,suffix): return len([a for a in addrs if a.endswith(suffix)]) def makeAcronym(words): acro = "" for w in words: acros += w[0] return acro def makeAcronym(words): ''.join([w[0] for w in words]) ============= Problem 3: lists of size 2 cause denominator to be zero in both cases, division b zero doesn't make sense mathematically, and for int values causes an error (for float too). the list is sorted so that low and high values occur first and last, respectively, and slicing removes them def computeScore(scores): low = min(scores) high = max(scores) lowc = scores.count(low) highc = scores.count(high) return (sum(scores)-low*lowc-high*highc)/(len(scores)-lowc-highc) # alternative def computeScore(scores): low = min(scores) high = max(scores) nlist = [] for s in scores: if s != low and s != high: nlist.append(s) return sum(nlist)/len(nlist) ============== Problem 5 ============== def getScore(filename,uname): file = open(filename) score = 0 lineNum = 0 for line in file: lineNum += 1 parts = line.split(",") if parts[1] == uname: score += lineNum file.close() if score == 0: return "NO SCORE" return score -- to score just top five, add scoreCount = 0 before loop, increment scoreCount += 1 in if statement and change if statement to guard: if parts[1] == uname and scoreCount < 5: # first alternative def getScore(filename,uname): file = open(filename) score = 0 for i,line in enumerate(file): parts = line.split(",") if parts[1] == uname: score += (i+1) # second alternative def getScore(filename,uname): file = open(filename) score = 0 nlist = [] for line in file: nlist.append(line) for line in nlist: parts = line.split(",") if parts[1] == uname: score += nlist.index(line)+1