CS106 Mid-term Quiz
Not counted in your grade.
Q1
Write code to create a variable message that refers to a string Hello world .
Answer: message = “Hello world”
Q2
Write code to create a variable aList that refers to an empty list.
Answer: aList = [] or aList = list()
Q3
Write code to create a variable aList that refers to a list that contains the integers 1, 2, …,
100.
Answer: aList = range(1, 101)
Q4
Write code using a for loop that does itembased iteration of a list acids , print out each item on a separate line.
Answer: for acid in acids: print acid
Q5
Write the same code, using index-based iteration.
Answer: for idx in range(len(acids)): print acids[idx]
Q6
Write code that iterates over a list of strings acids that prints only the items that have length 7.
Answer: for acid in acids: if len(acid) == 7: print acid
Q7
Write code that, given these lists: guys = [ ‘Abe’, ‘Bob’ … ] girls = [‘Ann’, ‘Bea’ … ]
(each having the same length), prints out corresponding pairs, like this:
Abe and Ann
Bob and Bea
…
A7 for idx in range(len(guys)): print guys[idx] + “ and “ + girls[idx]
Q8
Write code that creates a list of sorted integers from 1 to 1000 that contains only those integers that are not a multiple of 3 nor a multiple of 7.
A8 res = [] for i in range(1, 1001): if i % 3 == 0: continue if i % 7 == 0: continue res.append(i)
# you could also create a list with all numbers and then remove some, but that will be slow and problematic.
# Next slide has alternative solution.
A8 res = [] for i in range(1, 1001): if i % 3 != 0 and i % 7 != 0: res.append(i)
Q9
Write code to create a variable color that refers to a tuple containing integers 255, 66, 255.
Answer: color = (255, 66, 255)
Q10
Write code that when given a list of strings cheeses, prints out each cheese on a line, preceded by its number in the list and a dot.
E.g.,
1. Cheddar
2. Gouda
3. Venezuelan Beaver Cheese
A10 for idx in range(len(cheeses)): print str(idx + 1) + “, “ + cheeses[idx]