# Midterm #2 Solutions # November 15, 2012 # CODE BLOCK ANSWERS ARE BELOW THE PROGRAMS # PROGRAMS PROVIDED COMPLIMENTS OF THE CLASS # (Minor editing in spots by Dr. V) # ATTRIBUTION IS GIVEN ABOVE EACH PROGRAM # NOTE THAT THERE ARE USUALLY MANY DIFFERENT # VALID WAYS TO CODE EACH OF THESE TASKS # 1. by Chris S. name = raw_input("Enter a name from the list: ") for j in range(0,len(records)): if records[j][0] == name: print "this persons favorite number is", records[j][4] new = input("What do you like the new favorite number to be? ") records[j][4] = new # 2. by James K. import random randnums = [] for j in range(1,101): rand = random.randint(1,100) randnums.append(rand) count = 0 for j in range(1,101): if j not in randnums: count = count + 1 print count, "numbers from 1 to 100 do not appear in this list." # 3. by Tom R. def textify(phrase): new = "" for letter in phrase: if letter not in "aeiou": new = new + letter print new return new # 4. by Brandon W. vowels = "aeiou" word = raw_input("Enter any word:") word = word.strip() word = word.lower() count = 0 for j in range(0,len(word)-1): if word[j] in vowels and word[j+1] in vowels: count = count + 1 if count > 0: print "The word", word, "contains", count, " pairs of consecutive vowels." else: print "The word", word, "does not contain consecutive vowels." # 5. by Paige S. quiz = input("Which quiz number would you like the average of?") sum = 0 for j in range(0,len(gradebook)): sum = sum + gradebook[j][quiz-1] num = len(gradebook) avg = float(sum)/num print "The class average on that particular quiz was", str(avg)+"." # 6. by Adam G. # Note that we work backwards through the word list! # This is so that deleting a word will not affect # the remaining words that we have left to check. def prune(wordlist): letter = raw_input("Enter a letter: ") count = 0 for j in range(len(wordlist)-1,-1,-1): if letter in wordlist[j]: del wordlist[j] count = count + 1 print "There were", count, "words removed from the list." return wordlist # 7. by Luke S. num = input("Enter a two-digit number: ") while num < 10 or num > 99: num = input("A TWO-digit number: ") for j in range(0,len(records)): if records[j][4] <= num+3 and records[j][4] >= num-3: print records[j][0], records[j][1] # CODE BLOCK ANSWERS The squish of 3 and 8 is 20 rrr aaa The answer is 11 ["for", "lax", "two", "tub", "wit", "fit"] [6, 10, 11, 12, 13, 14] The rabbit has vanished. hannah a g n i m u i d ['r', 'n', 'u', 'm'] [7, 2, 3] # DEBUGGING ANSWERS # The corrected programs appear below def findlarge(numlist): max = numlist[0] for j in range(0,len(numlist)): if numlist[j] > max: max = numlist[j] return max # Note that the first line below should really be # for j in range(len(records)-1,-1,-1): # in order for the program to run properly. for j in range(0,len(records)): if records[j][3] == "red": del records[j] else: print records[j]