Exercises based on Labs, to review for the final **Lab3: Quiz: Finish the following two versions of contains1: def contains1(c,s): '''c is a char and s is a str. Return True if s contains c and false otherwise. ''' for i in s: if i == c: def contains2(c,s): '''c is a char and s is a str. Return True if s contains c and false otherwise. ''' found = False for i in s: if i == c: **Lab4: #1. At least one of the four potions is poisonous def hint1(p1, p2, p3, p4): return p1 or p2 or p3 or p4 #2. p2 is not poisonous def hint2(p2): return not p2 #3. At least one of p1 and p3 is poisonous def hint3(p1,p3): return p1 or p3 #4. At least one of p3 and p4 is not poisonous def hint4(p3,p4): return not p3 or not p4 #5. Exactly one of p1, p3, and p4 is poisonous def hint5(p1, p3, p4): return (p1 and not p3 and not p4) or\ (p3 and not p1 and not p4) or\ (p4 and not p1 and not p3) def solution(p1, p2, p3, p4): h1 = hint1(p1, p2, p3, p4) h2 = hint2(p2) h3 = hint3(p1, p3) h4 = hint4(p3, p4) h5 = hint5(p1, p3, p4) return h1 and h2 and h3 and h4 and h5 for p1 in [True,False]: for p2 in [True,False]: for p3 in [True,False]: for p4 in [True,False]: if solution(p1,p2,p3,p4): print (p1,p2,p3,p4, "is a solution!") # #Output this produces: #True False False False is a solution! #False False True False is a solution! # Great exercise for booleans -- p4 True means that potion 4 is poisonous -- solution is true if all hints evaluate to True -- Quiz: what does h1(False,False,False,False) evaluate to? what does h4(False,True) evaluate to? ** Lab5 student_grades = [['999888777', 78.0], ['111222333', 90.0], ['444555666', 83.0]] # Here is an example of a nested loop. TODO: Run and trace this until you are sure you understand it for student in student_grades: print(student) for x in student: print(x) -- Quiz: Trace on paper/board: student: x: # Now we'll start using a list of measurements measurements = [[33, 34, 30], [29, 31, 34], [28, 27, 30]] # TODO Write code here to print the average of each inner list # For example, for 'measurements', the averages are 32.333333, 31.333333, and 28.333333 print ("about to print the average of each inner list") for dataset in measurements: total = 0.0 for datapoint in dataset: total = total + datapoint print("the average of the values in",dataset, "is", total / len(dataset)) -- Quiz: Trace on paper/board dataset: total: # TODO Now do the same thing, but using the builtin function "sum". # enter 'help(sum)' in the Shell to see how to use it. print("about to print the average of each inner list...again") for dataset in measurements: print("the average of the values in", dataset, "is", sum(dataset) / len(dataset)) # TODO read the header and docstring for function 'where' (below). # Here, create a set of at least 5 test cases for 'where' and call 'grade' # as in lab3 (grade is below). Then, write function 'where' and test it. grade(where('abcdeddw x','d'),3) grade(where('a','a'),0) grade(where('abcdeddw x','x'),9) grade(where('abcdeddw x','z'),-1) grade(where('','z'),-1) def where(s,c): '''Given string s and single-character string c, return the position of the first occurrence of c in s. If c is not in s, return -1.''' # Do not use any string methods, but you can use functions in __builtins__ # # Remember that the positions of strings and list are numbered, starting # at 0. s = 'next'; s[0] is 'n'; s[1] is 'e'; and so on. # if not c in s: return -1 else: for i in range(len(s)): if s[i] == c: return i -- Quiz: Trace on board/paper s: 'abc' c: 'b' i: String method that does this: 'abc'.find('b') ** Lab6 -- Quiz >>> l = [[12.0,1.0,3.0],[2.0,3.0],[66.1,77.1]] >>> l[0] >>> l[1] >>> l[2] >>> l[0][0] >>> l[0][2] >>> l[2][0] >>> l[2][1] >>> -- Added some print statements to the solution to show what is happening at each point def inputTemperatureData(filename): '''Open the specified filename, read past the three-line header, read in the temperature data on the file, and close the file. Return the temperature data in the form of a list of lists, where each list element is a list of 12 temperature readings.''' # Hint: use readline to read the first three lines, and then # a while loop to read the numbers # # Hint: you need to convert the input from strings to # to floats. f = open(filename) f.readline() f.readline() f.readline() data = [] line = f.readline() while line != "": nums = line.split() flt_nums = [] for n in nums: flt_nums.append(float(n)) data.append(flt_nums) line = f.readline() f.close() return data def printDataPoint(tempData,mo,yr): '''tempData is the data structure returned by inputTemperatureData. mo is an integer in the range 0 to 11. yr is in the range 0 to len(tempData) - 1. Print the temperature for that month and that year. Suppose mo is 1 and yr is 3. The output should look like this (assuming the value is 65.7): The ave. monthly temperature during Feb in year 4 is 65.7. ''' mos = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'] print("The ave. monthly temperature during",mos[mo],"in year",yr,"is", format(tempData[yr][mo],".2f")) --- Having a list of months might be useful for printing elsewhere; better than a big if-elif statement def avgTempMarch(tempData): '''Return the average temperature for the month of March as a float for all years in tempData. tempData is the data structure returned by inputTemperatureData.''' total = 0 for year in tempData: total += year[2] return float(total)/len(tempData) --- The structure of tempData is [[data for year 0][data for year 1]...] --- year: [the 12 values for a single year] --- year[3]: the march value for that year --- len(tempData) is the number of years for which we have data def avgTemp(tempData, mo): '''Return the average temperature for month mo as a float for all years in tempData, where mo is an integer between 0 and 11, representing January to December, respectively. tempData is the data structure returned by inputTemperatureData.''' total = 0 for year in tempData: total += year[mo] return float(total)/len(tempData) --- Just like the above, except that 'mo' is a parameter def higherAvgTemp(tempData, mo1, mo2): '''Return either mo1 or mo2 (integers representing months in the range 0 to 11), whichever has the higher average temperature for all years in tempData. If the months have the same average temperature, then return -1. tempData is the data structure returned by inputTemperatureData.''' def avgTemps (tempData): ''' Return the average of all the temperatures stored in tempData. tempData is the data structure returned by inputTemperatureData.''' total = 0 for year in tempData: for mo in year: total += mo return float(total)/(len(tempData) * 12) ** Lab7 >>> s1 = "I poured Spot remover on my dog." >>> s2 = "Now he's gone." >>> s1[4:9] 'ured ' >>> s2[-1] '.' >>> s2[:7] "Now he'" >>> s1[6:] 'ed Spot remover on my dog.' >>> s1[:3] + s1[4:] 'I pured Spot remover on my dog.' >>> lst = [1,2,3] >>> help(list.extend) Help on method_descriptor: extend(...) L.extend(iterable) -- extend list by appending elements from the iterable >>> lst.extend([44,55]) >>> lst [1, 2, 3, 44, 55] >>> lst.extend(range(2,5)) >>> lst [1, 2, 3, 44, 55, 2, 3, 4] >>> lst.extend("Dog") >>> lst [1, 2, 3, 44, 55, 2, 3, 4, 'D', 'o', 'g'] >>> lst.remove(44) >>> lst.remove(55) >>> lst [1, 2, 3, 2, 3, 4, 'D', 'o', 'g'] >>> lst = [] >>> lst1 = [0,1,2] >>> lst2 = ["Spot","remover"] >>> lst3 = [[3,4],[5,6]] >>> lst.append(lst1) >>> lst [[0, 1, 2]] >>> lst.append(lst2) >>> lst [[0, 1, 2], ['Spot', 'remover']] >>> lst.append(lst3) >>> lst [[0, 1, 2], ['Spot', 'remover'], [[3, 4], [5, 6]]] >>> lst[1] ['Spot', 'remover'] >>> lst[2] [[3, 4], [5, 6]] >>> lst[3] Traceback (most recent call last): File "", line 1, in IndexError: list index out of range >>> lst[2] [[3, 4], [5, 6]] >>> lst[2][0] [3, 4] >>> lst[2][0][1] 4 >>> Write code that inputs an int between 1 and 5 from the user, and creates a list called "lst" that contains that many empty lists. For example, if the user enters 3, your code should create [[],[],[]]. >>> num = int(input("Enter an int between 1 and 5 ")) >>> lst = [] >>> for i in range(num): ... lst.append([]) ... >>> lst [[], [], []] --- Trace: i: lst: >>> board = [] >>> for i in range(3): ... row = [] ... for col in range(3): ... row.append("*") ... board.append(row) ... >>> board What is printed here? >>> --- For the following, make sure you can see which variables change their values >>> def fun1(s): ... s * 3 ... return None ... >>> s1 = "You're unique like everyone else" >>> fun1(s1) >>> s1 "You're unique like everyone else" >>> def fun2(s): ... return s * 3 ... >>> s1 = fun2(s1) >>> s1 "You're unique like everyone elseYou're unique like everyone elseYou're unique like everyone else" >>> def fun3(lst): ... lst.append("construction") ... >>> x = [3,4,5] >>> fun3(x) >>> x [3, 4, 5, 'construction'] >>> >>> d = [["knock knock","who's there"],["cash","cash who?"],["No thanks, but I would like a peanut instead","Groan"]] >>> d [['knock knock', "who's there"], ['cash', 'cash who?'], ['No thanks, but I would like a peanut instead', 'Groan']] >>> person1 = 0 >>> person2 = 1 >>> for i in d: ... print("P1:",i[person1]) ... print("P2:",i[person2]) ... print() ... P1: knock knock P2: who's there P1: cash P2: cash who? P1: No thanks, but I would like a peanut instead P2: Groan