1/99
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
What does the following evaluate to?
"UID12345"[3:].lower().isdigit()
a. True
b. False
c. 12345
d. D12345
e. None
a. True
Which of the following is True?
a. "bcd" < "abc"
b. "BCD" < "abc"
c. "bcd" < "ABC"
d. "abbc" < "abb"
e. "A2" < "A11"
b. "BCD" < "abc"
What does the following code print?
s = "this is a test"
words = s.split(" ")
words[3] = "?" * len(words[1])
print(" ".join(words))
a. This is a test
b. This is ???? test
c. This is a ????
d. This is a ?
e. None of the above because an IndexError occurs
c. This is a ????
What will be printed and in what order?
nums = [10, 20, 30, 40, 50]
print(nums[1])
print(nums[1:3])
a. 40 and [20, 30]
b. 50 and [20, 30, 40]
c. 50 and [20, 30]
d. IndexError: list index out of range
c. 50 and [20, 30]
What is the output of the following code?
my_list = ["movies", "friends", "family", "books"]
my_list.append("music")
my_list.pop(3)
my_list.sort()
print(my_list)
a. ['books', 'family', 'friends', 'movies',]
b. ['books', 'family', 'friends', 'movies', 'music']
c. ['movies', 'friends', 'family', 'books', 'music']
d. ['family', 'friends', 'movies', 'music']
d. ['family', 'friends', 'movies', 'music']
What will be printed and in what order?
nums = [1, 2, 3]
words = ["one", "two", "three"]
print(words[nums.index(2)])
words = ["zero"] + words
nums = [0] + nums
print(words[nums.index(2)])
a. two, two
b. two, one
c. one, two
d. two, three
a. two, two
What will be printed and in what order?
d1 = {1 : "one", 2 : "two", 3 : "three"}
d1[0] = "zero"
d2 = dict()
for k in d1:
d2[d1[k]] = k
print(d1[3])
print(d2["three"])
a. three, KeyError
b. three, 3
c. 3, three
d. KeyError, 3
b. three, 3
What is the output of the following code?
words = ["one", "two", "three", "four", "five"]
d = {}
for word in words:
if len(word) not in d:
d[len(word)] = [word]
else:
d[len(word)] += [word]
print(d)
a. {3: ['one', 'two'], 5: ['three'], 4: ['four', 'five']}
b. {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}
c. {'one': 3, 'two': 3, 'three': 5, 'four': 4, 'five': 4}
d. {3: ['two'], 5: ['three'], 4: ['five']}
a. {3: ['one', 'two'], 5: ['three'], 4: ['four', 'five']}
Consider the following dictionary.
person = {}
person['name'] = 'Vinodh Balasubramanian'
person['address'] = {
'street': '1, Gangai Amman Koil Street',
'city': 'Chennai',
'state': 'Tamil Nadu',
'zip': 600014
}
How will you access the name of the city (i.e., Chennai) that this person lives in?
a. person['city']
b. person[1]['city']
c. person['address'][1]
d. person['address']['city']
d. person['address']['city']
10. Which of the following is the correct way to the attribute x in Point p?
Point = namedtuple("Point", ['x', 'y'])
p = Point(10, 20)
a. p{x}
b. p("x")
c. p[x]
d. p["x"]
e. p.x
e. p.x
Which of the following cannot be used as a key for a Python dictionary?
a. tuples
b. namedtuples
c. lists
d. strings
e. negative integers
c. lists
What is the output of the following code?
a = ([10], 30)
b = a
c = b[0]
c.append(20)
b = b + (40, 50)
print(a)
a. ([10, 20], 30)
b. ([10, 20], 30, 40, 50)
c. ([10], 30, 40, 50)
d. ([10], 30)
a. ([10, 20], 30)
What is the value in my_list after this code is run?
my_list = ["Alice", "Bob", "Charlie", "Dennis"]
your_list = my_list
my_list.remove("Alice")
your_list.remove("Dennis")
print(my_list)
a. ["Bob", "Charlie", "Dennis"]
b. ["Bob", "Charlie"]
c. ["Alice", "Bob","Charlie", "Dennis"]
d. ["Alice", "Bob","Charlie"]
b. ["Bob", "Charlie"]
What is the value of x after this code is run? [options on next page]
orig = [1, [2, 3]]
x = orig
y = copy.copy(orig)
y[0] = 4
y[1][0] = 5
y[1][1] = 6
print(x)
6
a. [1, [2, 3]]
b. [4, [2, 3]]
c. [4, [5, 6]]
d. [1, [5, 6]]
d. [1, [5, 6]]
What is the value of x after this code is run?
orig = [1,[2, 3]]
x = orig
y = copy.deepcopy(orig)
y[0] = 4
y[1][0] = 5
y[1][1] = 6
print(x)
a. [1, [2, 3]]
b. [4, [2, 3]]
c. [4, [5, 6]]
d. [1, [5, 6]]
a. [1, [2, 3]]
Using which command in a function body makes the function a generator function?
a. yield
b. return
c. generate
d. next
a. yield
What will be printed and in what order?
def square_numbers(nums):
for i in nums:
yield (i*i)
my_nums = square_numbers([1,2,3,4,5])
for num in my_nums:
print(num)
a. 1, 4, 9, 16, 25
b.
c. 1
d. 25
a. 1, 4, 9, 16, 25
What is the output of the following code?
def foo(x):
return x % 2 == 1
def special_sum(nums, check):
total = 0
for num in nums:
if check(num):
total += num
return total
print(special_sum([1, 3, 4, 9], foo))
a. 1
b. 4
c. 13
d. 17
e. None
c. 13
Which of the following statements are true?
a. When you open a file for reading, if the file does not exist, an error occurs
b. When you open a file with mode "w", if the file does not exist, a new file is created
c. When you open a file with mode "w", if the file exists, the existing file is
overwritten with the new file
d. All of the above
d. All of the above
What is the type of data and lines in the following code?
f = open("file.txt")
data = f.read()
lines = data.split('\n')
a. data is a string and lines is a list
b. data is a list and lines is a string
c. both data and lines are lists
d. both data and lines are strings
a. data is a string and lines is a list
What is printed?
data = [["alice", "in", "wonderland"], ["a","b","c"], ["hello"]]
print(data[2][0][1])
a. a
b. hello
c. c
d. o
e. e
d. o
What is printed?
data = {1: {"f": "Alice"}, 2: {"f": "Bob", "l": "Smith"}}
print(data[1]["f"], data[1].get("l", "Doe"))
a. Alice
b. Alice Doe
c. Alice Smith
d. Bob Doe
e. Bob Smith
b. Alice Doe
What is printed?
data = [["A", "B", "C"], [1,2,3], [4,5,6], [7,8,9]]
idx = data[0].index("B")
total = 0
for row in data[1:]:
total += row[idx]
print(total)
a. 6
b. 12
c. 13
d. 15
e. 24
d. 15
What is the output of the above snippet?
mapping = {}
for i in range(3):
for j in range(2):
mapping[(i,j)] = i + j
print(len(mapping), mapping[(1,1)])
a. 2 2
b. 3 1
c. 3 2
d. 6 1
e. 6 2
e. 6 2
Consider the following code:
movies = [
{"name": "m1", "actors": ["A", "B"], "genres": ["X"]},
{"name": "m2", "actors": ["C", "D"], "genres": ["X", "Y"]},
{"name": "m3", "actors": ["A", "C"], "genres": ["Y", "Z"]},
{"name": "m4", "actors": ["B", "C"], "genres": ["X", "Z"]},
]
# key: actor name, val: list of unique genres actor has acted in
actor_genres = {}
for movie in movies:
for actor in movie["actors"]:
for genre in movie["genres"]:
if not actor in actor_genres:
_____________________
a. actor_genres[actor] = []
What does the following code print?
mapping = {}
my_list = []
keys = [ 'k0', 'k1', 'k2' ]
for k in keys:
mapping[k] = my_list
for i in range(3):
k = keys[i]
mapping[k].append(i)
print(mapping['k0'], mapping['k1'])
a. None None
b. [0] [1]
c. [1] [2]
d. [0, 1, 2] [0, 1, 2]
e. k0 k1
d. [0, 1, 2] [0, 1, 2]
What does the following code print?
def foo(obj_a, obj_B):
return obj_a + obj_b
y = foo
a = 1
b = 2
c = 3
print(y(a,b) + y(b,c))
a. 6
b. 8
c. 35
d. Code generates TypeError
e. Code prints representation of foo
b. 8
What does the following code print?
def foo(input_object):
for item in input_object
item = item + 1
return sum(input_object)
num_list = [1,2,3]
print(foo(num_list))
a. 6
b. 9
c. [1, 2, 3]
d. [2, 3, 4]
a. 6
Just like infinite iteration, infinite recursion make a program run forever
a. True
b. False
b. False
What does f("ABC") return?
def f(text):
if len(text) <= 1:
return text
return f(text[1:]) + text[0]
a. A
b. C
c. ABC
d. CBA
e. None of the above because there is a stack overflow
d. CBA
What does ternary(7) return?
def ternary(n):
if n < 3:
return str(n)
else:
quo = n // 3
rem = n % 3
return ternary(quo) + ternary(rem)
a. 3
b. 7
c. 12
d. 21
e. None of the above because there is a stack overflow
d. 21
Which call to foo will NOT cause an AssertionError? [see options on next page]
def foo(x, y):
assert type(x) == int and type(y) == int
assert x % 2 == 0 and x > y
return x y
a. foo("4", 2)
b. foo(2, 2)
c. foo(3, 2)
d. foo(4, -3)
e. foo(4, 2.0)
d. foo(4, 3)
What lines of code execute in the following?
a = 1 # line 1
b = 0 # line 2
c = a/b # line 3
try:
print("a/b is " + str(c)) # line 4
except:
print("Got a divide-by-zero error!") # line 5
print("exiting") # line 6
a. Lines 1, 2, and 3
b. Lines 1, 2, 3, and 4
c. Lines 1, 2, 3, and 5
d. Lines 1, 2, 3, and 6
e. Lines 1, 2, 3, 4, 5, and 6
a. Lines 1, 2, and 3
What does the following code print?
before = [10, 20]
after = []
for i in range(3):
try:
after.append(before[i])
except:
after.append(1)
print(after)
a. [10, 20]
b. [10, 20, -1]
c. [10, 20, -1,-1]
d. [10, 20, 20]
e. [20, -1,-1]
b. [10, 20, -1]
What does the following print?
x = 1
y = 2
def f(x):
x = 2*3
return x + y
w = f(x)
v = f(y)
print(str(3*x) + str(v) + "!")
A. "318!" B. "2418!" C. "3010! D. "218!"
A. "318!"
For the next few questions consider the following code that prints a grid displaying the areas where hurricanes commonly form in North-East Kansas. In particular, to take the border into account, the grid just contains the entries of the lower triangle of the
whole grid. An "H" represents a hurricane usually forms in this area and a "." meansmhurricanes avoid this area. The only input is the size of the grid we want patterns for.
def radar(n=5):
for i in range(n):
for j in range(i):
if (i + j) % 2 == 0:
print("H", end = "")
else:
print(".", end = "")
print() # default end is "\n"
2. The rst line of output from radar() corresponds to which string?
A. "\n" B. ".\n" C. "H\n" D. ".H\n"
3. What characters appear on the top diagonal of the shape printed by radar(5)?
(ignore lines that are just white space)
A. 4 periods B. 4 H's C. 2 periods and 2 H's
4. What characters (ignoring whitespace) would be printed by radar() in the rst column if
the programmer had forgotton the parantheses in the condition in the radar function so that
that line instead looked like this: if i + j % 2 == 0:
A. 4 periods B. 4 H's C. 2 periods and 2 H's
2. A. "\n".
3. A. 4 periods
4. A. 4 periods
For the following, assume the initial code executed is as follows (if a question contains code that modi es the objects, those changes should not be considered in other questions):
import copy
genres = ["g1", "g2", "g3"]
movies = [
{"title": "A", "year": 17, "style": "short", "genres": ["g1"]},
{"title": "B", "year": 18, "style": "long", "genres": ["g2"]},
{"title": "C", "year": 19, "style": "short", "genres": ["g3"]},
{"title": "D", "year": 19, "style": "long", "genres": ["g1", "g2", "g3"]}
]
def first_n(movies, n):
while len(movies) > n:
movies.pop() # by default, removes last item
return movies
5. What does the following print?
genres_new = genres
genres.remove("g3")
genres_new.remove("g1")
print(genres)
A. ["g1", "g2"] B. ["g1", "g2", "g3"] C. ["g2"] D. ["g2", "g3"]
6. What does the following print? Be careful!
movies1 = first_n(movies, 2)
movies2 = first_n(movies, 3)
print(len(movies1), len(movies2))
A. 0 0 B. 2 0 C. 2 2 D. 2 3 E. 4 4
7. What does the following print?
cp = copy.copy(movies) # shallow copy
movies.append(0)
movies[0]["year"] = 16
print(cp[0]["year"], len(cp))
A. 16 4 B. 16 5 C. 17 0 D. 17 4 E. 17 5
8. If copy.copy were replaced with copy.deepcopy in the previous question, what would the
code print?
A. 16 4 B. 16 5 C. 17 4 D. 17 5 E. 17 6
5. C ["g2"]
6. C. 2 2
7. A. 16
8. C. 17 4
def curses(x):
if x == 0:
return 1
else:
return curses(x-1) * 2
def swap(lis, x, y):
tmp = lis[y]
lis[y] = lis[x]
lis[x] = tmp
def mix(a_list, x):
swap(a_list, x, x-1)
if x > 0:
mix(a_list, x-1)
9. Which statement creates a new reference to the curses function object?
A. f := curses B. f = curses C. f = curses() D. f = curses(x) E. f = curses(5)
10. What does curses(5) return?
A. 1 B. 10 C. 16 D. 8 x
11. Which call causes a stack overow (meaning we create too many frames)?
A. curses(0) B. curses(0.0) C. curses(1/0) D. curses(-1) E. curses(None)
12. What does my list look like after the following code?
my_list = ["A", "B", "C"]
mix(my_list, 2)
A. [ ] B. [\A", \B", \C"] C. [\B", \A", \C"] D. [\C", \B", \A"] E. [\A", \B"]
9. B. f = curses
10. B. f = curses
11. D. curses(-1)
12. C. [\B", \A", \C"]
For the following, assume the initial code executed is as follows (if a question contains code that modi es the objects, those changes should not be considered in other questions):
gens = ["g1", "g2", "g3"]
movs = [{"title": "A", "year": 17, "style": "short", "genres": ["g1"]}]
def chk(movies, year):
assert type(year) == int
assert type(movies[0]) == dict
# TODO: finish this function
14. Which call will NOT cause an AssertionError?
A. chk(gens, "18") B. chk(gens, 18) C. chk(movs, "18") D. chk(movs, 18)
16. What should replace ???? to trigger the most informative exceptions when year isn't an iont?
def filter_by_year(movies, year):
if type(year) != int:
????
# TODO: finish writing this function
A. return TypeError("year shoud be int")
B. return ValueError("year shoud be int")
C. raise TypeError("year shoud be int")
D. raise ValueError("year shoud be int")
14. D. chk(movs, 18)
16. C. raise TypeError("year shoud be int")
from collections import namedtuple
Player = namedtuple("Player", ["name", "rating", "club", "country"])
hazard = Player(name="Eden Hazard", rating=91,
club="Chelsea", country="Belgium")
pulisic = Player(name="Christian Pulisic", club="Chelsea",
rating=79, country="United States")
messi = Player(name="Lionel Messi", club="Barcelona",
country="Argentina", rating=94)
players = ["Kevin De Bruyne", "Christiano Ronaldo",
"Harry Kane", "Hugo Lloris", "Don Smart"]
salah = {}
salah["name"] = "Mo Salah"
salah["nationality"] = "Egypt"
salah["jersey"] = 11
salah["nationality"] = "Egypt"
17. What does pulisic.club evaluate to?
A. \Chelsea" B. Error C. 79 D. club E. rating
18. How can we switch Eden Hazard's club to Real Madrid?
A. hazard.club = "Real Madrid"
B. hazard[1] = "Read Madrid"
C. hazard["club"] = "Read Madrid"
D. hazard = Player(name=hazard.name, rating=hazard.rating, club="Real
Madrid", country=hazard.country)
19. How can we get only the rst 3 players in players?
A. players[3] B. players[0:3] C. players[0:2] D. players(3) E. players[0, 1, 2]
20. What is len(salah)? Careful!
A. 3 B. 4 C. 5 D. 6 E. 8
21. Which data type would you not be able to use if you wanted to store hazard, pulisic, and
messi in a variable called data and access them using data[0], data[1], and data[2]?
A. dict B. list C. set D. tuple
17. A. \Chelsea"
18.D. hazard = Player(name=hazard.name, rating=hazard.rating, club="Real Madrid", country=hazard.country)
19. B. players[0:3]
20. A. 3
21. C. set
What will be in the file.txt file after this code runs?
f = open("file.txt", "w")
f.write("hi")
f.close()
f = open("file.txt", "w")
f.write("I love")
f.write("Python")
f.close()
A. "Python" B. "I lovePython" C. "I love Python" D. "hi\nI love\nPython"
B. "I lovePython"
What is a good reason to serialize Python data structures to a JSON le instead of just
using the data structures?
A. Files remain after rebooting B. Files are faster C. JSON supports more types
A. Files remain after rebooting
A key in a Python dict may be an integer (T/F). A. True B. False
A. True
A key in a JSON dict may be an integer (T/F). A. True B. False
b. False
In which format is everything a string? A. CSV B. JSON C. Excel spreadsheet
A. CSV
Rows of a CSV are normally delimited by which of the following?
A. commas B. semicolons C. quotes D. new lines
D. new lines
Which of the following is a valid boolean in JSON?
A. true B. True C. TRUE D. absolutely
A. true
Which of the following is not a sequence?
A. tuple B. list C. string D. dictionary
D. dictionary
What will be printed after this code runs?
s = "Nice day, isn't it?"
words = s.split(" ")
print(words.pop(-1))
A. ? B. it? C. isn't it? D. Nice E. Nice day, isn't
B. it?
What will be in the le after this code runs?
f = open("file.txt", "w")
f.write("Hello")
f.close()
f = open("file.txt", "w")
f.write("World")
f.close()
f = open("file.txt")
data = f.read()
data = "!!!!!"
f.close()
A. !!!!! B. Hello C. World D. HelloWorld!!!!! E. Hello World !!!!!
C. World
What is the output of the following code?
msg = "Hey220"
msg.upper()
for i in range(len(msg)):
if msg[i].isdigit():
print(msg[i - 2])
break
A. 2 B. E C. e D. Hey220 E. HEY220
C. e
What will be printed after this code runs?
a = [1]
b = [2]
c = b
c.append(1)
c.sort()
a.append(b)
print(a, b)
A. [1, [2]] [2]
B. [1, 1, 2] [1, 2]
C. [1] [1, 2]
D. [1, [1, 2]] [1, 2]
E. [1, [2]] [2]
D. [1, [1, 2]] [1, 2]
What is the output of the following code? Assume Python version is 3.6 or above.
d = {1: "one", 2: "two", 3: "three"}
d[0] = "zero"
d2 = dict()
for k in d:
d2[d[k]] = k
print(len(d2), list(d2.keys())[0])
A. 4 0 B. 4 1 C. 4 zero D. 4 one
D. 4 one
Which of the following will access Jenny's math grade?
student = {}
student["name"] = "Jenny"
student["grades"] = {"math": 90, "biology": 95}
A. grades["math"]
B. grades["Jenny"]["math"]
C. student["grades"]["math"]
D. student["Jenny"]["math"]
C. student["grades"]["math"]
What is the output of the following code?
my_list = ["Alice", "Bob", "Evelyn"]
your_list = my_list[:]
my_list.append("Dennis")
your_list.pop(0)
print(your_list)
A. ["Bob", "Evelyn"]
B. ["Alice", "Bob", "Evelyn"]
C. ["Bob", "Evelyn", "Dennis"]
D. ["Alice", "Bob", "Evelyn", "Dennis"]
A. ["Bob", "Evelyn"]
What is the output of the following code?
a = (1, 2, 3)
a[0] = a[1] + a[2]
print(a[1])
A. 1 B. 2 C. 3 D. 5 E. Nothing because the program crashes
E. Nothing because the program crashes
What is the value of x after the code is run?
import copy
orig = [1, (2, 3)]
x = orig
y = copy.copy(orig)
x[0] = 4
x[1] = (5, 6)
print(y)
A. [1, (2, 3)] B. [1, (5, 6)] C. [4, (2, 3)] D. [4, (5, 6)]
A. [1, (2, 3)]
What is the output?
def mystery(item_list):
count = 0
for item in item_list:
if type(item) == list:
count += mystery(item)
else:
count += 1
return count
print(mystery([[1, 2], 3, [4, 5, 6], 7]))
A. 0 B. 4 C. 7 D. 28
C. 7
What is the output?
def foo(n):
if n > 3:
return n + foo(n - 1)
return 0
print(foo(5))
A. 5 B. 9 C. 12 D. 15
B. 9
Which of the following will generate a list of words with a length longer than 7?
words = ["Psychology", "Bascom", "Noland", "Ingraham", "Soils"]
A. [len(w) for w in words if len(w) > 7]
B. [len(words) for w in words if len(words) > 7]
C. [words for w in words if len(words) > 7]
D. [w for w in words if len(w) > 7]
D. [w for w in words if len(w) > 7]
Which of the following will sort words by the length of each word, with the longest word
appearing rst?
words = ["Psychology", "Bascom", "Noland", "Ingraham", "Soils"]
A. sorted(words, key = len, reverse = True)
B. sorted(words, key = len)
C. sorted(words, key = lambda len, reverse = True)
D. sorted(words, key = lambda len)
A. sorted(words, key = len, reverse = True)
15. Which of the following will generate a dictionary with name to age mapping?
players = [{"name":"Alia", "jersey":17,"age":20},
{"name":"Brianna", "jersey":6, "age":19},
{"name":"Carl", "jersey":10, "age":21} ]
A. {k:v for (k, players["age"]) in players}
B. {d["name"]:d["age"] for d in players}
C. {d[0]:d[2] for d in players"
D. {k:v for (k, v) in players.items()}
{d["name"]:d["age"] for d in players}
Which of the following will correctly sort players by jersey number?
players = [{"name":"Alia", "jersey":17,"age":20},
{"name":"Brianna", "jersey":6, "age":19},
{"name":"Carl", "jersey":10, "age":21} ]
A. sorted(players, key = jersey)
B. sorted(players.items(), key = jersey)
C. sorted(players, key = lambda p:p["jersey"])
D. sorted(players.items(), key = lambda p:p["jersey"])
C. sorted(players, key = lambda p:p["jersey"])
airbnb = [{"name":"A", "room_id":837, "start_year":2021, "reviews":[""]},
{"name":"B", "room_id":389, "start_year":2021, "reviews":["","","*"]},
{"name":"C", "room_id":108, "start_year":2021, "reviews":["**","*"]},
{"name":"D", "room_id":237, "start_year":2020, "reviews":["*"]},
{"name":"E", "room_id":278, "start_year":2020, "reviews":["**","","**"]},
]
17. What does the following evaluate to? airbnb[-1]["reviews"][1]
A. "*" B. "*" C. ["*"] D. ["*", "", "**"] E. "reviews"
18. What does the following evaluate to?
airbnb[2]["reviews"].index(airbnb[1]["reviews"][2])
A. 0 B. 1 C. 2 D. "**" E. ""
19. What does the following evaluate to?
airbnb[1]["reviews"][:1] + airbnb[2]["reviews"][1:]
A. ["", "", "*"]
B. ["", "*"]
C. ["*"]
D. f"reviews": ["", "*"]g
20. Which of the following would generate a list of airbnb listing names, which have room id
greater than 250?
A. fkey: val for key, val in airbnb.items() if item["room id"] > 250g
B. [item if item["room id"] > 250 for item in airbnb]
C. [item["name"] for item in airbnb if item["room id"] > 250]
D. [item for item in airbnb if item["room id"] > 250]
17.A. "**"
18. B. 1
19. B. ["", "*"]
20. C. [item["name"] for item in airbnb if item["room id"] > 250]
Which of the following will result possibly refer to? Assume Python version is 3.6 or above.
result = []
for x in airbnb[1]:
result.append(x)
result
A. ["r", "o", "o", "m", " ", "i", "d"]
B. ["reviews", "start year", "room id", "name"]
C. ["name", "room id", "start year", "reviews"]
D. ["A", 837, 2021, [""]]
E. ["A", 837, 2021, ""]
C. ["name", "room id", "start year", "reviews"]
22. What will counts contain? Read the code carefully! Note: This question has an intentional semantic error.
counts = {} # Line 1
for item in airbnb: # Line 2
reviews = item["reviews"] # Line 3
for review in reviews: # Line 4
if review not in counts: # Line 5
counts[review] = 0 # Line 6semantic error
else: # Line 7
counts[review] += 1 # Line 8
A. f"": 0, "": 0, "": 0, "**": 0g
B. f"": 1, "": 1, "": 2, "**": 2g
C. f"*": 2, "*": 2, "": 1, "": 1g
D. f"": 1, "": 2, "": 3, "**": 4g
E. f"": 2, "": 2, "": 3, "**": 3g
23. How should line 6 be modi ed to x the semantic error?
A. counts[review] += 0
B. counts[review] += 1
C. counts[review] = []
D. counts.append(review)
E. counts[review] = 1
22. B. {"": 1, "": 1, "": 2, "**": 2}
23. E. counts[review] = 1
Assume that the initial code executed is as follows:
airbnb = [
{"name":"A", "room_id":837, "start_year":2021, "reviews":[""]},
{"name":"B", "room_id":389, "start_year":2021, "reviews":["","","*"]},
{"name":"C", "room_id":108, "start_year":2021, "reviews":["**","*"]},
{"name":"D", "room_id":237, "start_year":2020, "reviews":["*"]},
{"name":"E", "room_id":278, "start_year":2020, "reviews":["**","","**"]},
]
24. Which of the following will sort airbnb based on descending order of length of reviews?
A. sorted(airbnb, key = airbnb:len(d["reviews"]), reverse = True)
B. sorted(airbnb, key = lambda d:len(d))
C. sorted(airbnb, key = lambda d:len(d["reviews"]))
D. sorted(airbnb, key = lambda d:len(d["reviews"]), reverse = True)
E. sorted(airbnb, key = lambda airbnb:len(item) for item in airbnb)
24. D. sorted(airbnb, key = lambda d:len(d["reviews"]), reverse = True)
What will be printed? Read the code carefully!
buckets = {}
bucket = []
for item in airbnb:
start_year = item["start_year"]
if start_year not in buckets:
buckets[start_year] = []
buckets[start_year].append(item)
print(len(buckets[2020]), len(buckets[2021]))
A. 0 0 B. 2 3 C. 3 2 D. 5 0 E. 5 5
B. 2 3
For each question in this section, assume that the initial code executed is as follows:
from collections import namedtuple
Hurricane = namedtuple("Hurricane", ["name", "damage", "deaths", "mph"])
katrina = Hurricane(name = "Katrina", damage = "3.98B", deaths = "1836", mph = "175")
baker = {"name": "Baker", "damage": "2.55M", "deaths": "38", "mph": "105"}
26. What does katrina.deaths evaluate to?
A. "1836" B. 1836 C. "deaths" D. KeyError
27. Which of the two lines of code marked A and B will not execute successfully? Assume that if line A fails to execute, we comment it out and try to execute line B.
some_dict = {}
some_dict[katrina] = "Katrina - Category 5 hurricane" # line A
some_dict[baker] = "Baker - Category 2 hurricane" # line B
A. line A B. line B C. Both line A and line B D. Neither A nor B
28. What will be printed after this code runs?
import copy
some_list = [baker, katrina]
new_list1 = copy.copy(some_list)
new_list1[0]["name"] = new_list1[0]["name"].upper()
new_list2 = copy.deepcopy(some_list)
new_list2[0]["deaths"] = int(new_list1[0]["deaths"])
print(some_list[0]["name"], type(some_list[0]["deaths"]))
A. Baker
B. Baker
C. BAKER
D. BAKER
29. Which options sorts the hurricanes list in decreasing values of mph?
katrina = Hurricane("Katrina", "3.98B", "1836", "175")
sandy = Hurricane("Sandy", "2.34M", "546", "240")
baker = Hurricane("Baker", "2.55M", "38", "105")
hurricanes = [katrina, sandy, baker]
def extract(hurricane):
return -int(hurricane.mph)
A. sorted(hurricanes, key = extract())
B. sorted(hurricanes, key = extract(hurricane))
C. sorted(hurricanes, key = extract)
D. sorted(hurricanes, key = extract(hurricanes))
26. A. "1836"
27. B. line B
28. C. BAKER
29.C. sorted(hurricanes, key = extract)
Which of the following are the delimiters of the rows in a CSV le?
A. space B. newline C. comma D. semicolon
B. newline
Why is the following JSON le formatted incorrectly?
{
"Messi": {
"Stats": [91, 93, 85],
"Country": null,
"Club": `PSG'
}
}
A. Strings must be enclosed within double quotations
B. null used instead of None
C. List items must be strings
D. Dictionary keys must be integers
A. Strings must be enclosed within double quotations
What is the output of the following piece of code? Assume that the code does not crash due to exceptions. Also, assume that some file.txt contains the following content.
I promise
to always
close my files
f = open(`some_file.txt')
data = f.read()
lines = data.split(`\n')
print(type(data), type(lines))
A.
B. class `str'>
C.
D.
D.
What call to foo will not cause an AssertionError?
def foo(a, b):
assert type(a) == int and type(b) == int
assert a % 2 == 1 and a < b
return a + b
A. foo(12.0, 7.0)
B. foo(17, 11)
C. foo(12, 17)
D. foo(11, 17)
E. foo(12, 17.0)
D. foo(11, 17)
What is the output of the following piece of code?
input_data = [12, 3, 0, 2]
output_data = []
for number in input_data:
try:
output_data.append(12 // number)
except:
output_data.append(-1)
print(output_data)
A. [1, 4]
B. [1, 4, -1]
C. [1, 4, -1, 6]
D. [-1, 1, -1, -1]
E. ZeroDivisionError
Page
C. [1, 4, -1, 6]
What line is printed last when the following code is run?
my_list = [1.1, 0.3, 0.6]
for element in my_list:
try:
print("The element is:", element)
reciprocal = 1 // int(element)
print(reciprocal)
except ZeroDivisionError as e:
print("Oops!!!")
A. The element is: 0.6
B. The element is: 0.3
C. The element is: 1.1
D. ZeroDivisionError
E. Oops!!!
E. Oops!!!
Which of the following is mutable?
A. tuple B. string C. dictionary D. int
C. dictionary
What is the output of the following code?
s = "Welcome to CS 220!"
s = s.split(" ")
print(s[2][-1])
A. o B. S C. CS D. 220! E. IndexError
B. S
What will the following code print?
a = [1]
b = [2, 3]
c = [6, 7]
b = c
c.pop(-1)
b.append(a[-1])
print(a, b)
A. [1] [2, 3]
B. [1] [2, 3, 1]
C. [1] [6, 1]
D. [1] [6, 7, 1]
E. [2, 3] [6, 1]
C. [1] [6, 1]
What is the output of the following code?
colors_dict = {"Red": 25, "Orange": 23, "Yellow": 32, "Brown": 7}
colors_dict[0] = "Green"
print(colors_dict[23])
A. "Red" B. 25 C. "Orange" D. 23 E. KeyError
E. KeyError
What is printed from the following code?
import copy
monsters_v1 = ["Frankenstein", ["Vampire", "Mummy", "Ghost", "Werewolf"]]
monsters_v2 = copy.deepcopy(monsters_v1)
monsters_v1[1][0] = "Dracula"
monsters_v1[0] = "Sand monster"
print(monsters_v2)
A. ["Frankenstein", ["Vampire", "Mummy", "Ghost", "Werewolf"]]
B. ["Frankenstein", ["Dracula", "Mummy", "Ghost", "Werewolf"]]
C. ["Sand monster", ["Vampire", "Mummy", "Ghost", "Werewolf"]]
D. ["Sand monster", ["Dracula", "Mummy", "Ghost", "Werewolf"]]
A. ["Frankenstein", ["Vampire", "Mummy", "Ghost", "Werewolf"]]
What is printed from the following code?
import copy
monsters_v1 = ["Frankenstein", ["Vampire", "Mummy", "Ghost", "Werewolf"]]
monsters_v2 = copy.copy(monsters_v1)
monsters_v1[1][0] = "Dracula"
monsters_v1[0] = "Sand monster"
print(monsters_v2)
A. ["Frankenstein", ["Vampire", "Mummy", "Ghost", "Werewolf"]]
B. ["Frankenstein", ["Dracula", "Mummy", "Ghost", "Werewolf"]]
C. ["Sand monster", ["Vampire", "Mummy", "Ghost", "Werewolf"]]
D. ["Sand monster", ["Dracula", "Mummy", "Ghost", "Werewolf"]]
B. ["Frankenstein", ["Dracula", "Mummy", "Ghost", "Werewolf"]]
What is the output of the following code?
total = 0
halloween_dict = {
"Candy Corn": -1,
"Caramel Apples": 2,
"Jack O' Lanterns": 3,
"Skeletons": 10
}
total += halloween_dict.pop("Candy Corn")
halloween_dict.pop("Caramel Apples")
total += halloween_dict.pop("Jack O' Lanterns")
halloween_dict["Ghosts"] = total
print(halloween_dict)
A. {"Skeletons": 10, "Ghosts": 2}
B. {"Skeletons": 10, "Ghosts": 4}
C. {"Candy Corn": -1, "Caramel Apples": 2, "Jack O' Lanterns": 3,
"Skeletons":10, "Ghosts": 2}
D. {"Candy Corn": -1, "Caramel Apples": 2, "Jack O' Lanterns": 3,
"Skeletons": 10, "Ghosts": 4}
A. {"Skeletons": 10, "Ghosts": 2}
What values are printed by the code below?
def f(n):
if n > 5:
f(n-1)
print(n, end=" ")
f(9)
A. 9 8 7 6
B. 9 8 7 6 5
C. 5 6 7 8
D. 5 6 7 8 9
E. The program runs into a RecursionError
D. 5 6 7 8 9
What is the final value of letter list and number list after the following code is executed?
letter_list = ["B", "D", "E", "A", "C"]
letter_list = letter_list.sort(reverse = True)
number_list = [10, 50, 40, 20, 30]
number_list = sorted(number_list, reverse = True)
print(letter_list, number_list)
A. ["E", "D", "C", "B", "A"] [50, 40, 30, 20, 10]
B. ["B", "D", "E", "A", "C"] None
C. ["E", "D", "C", "B", "A"] [10, 50, 40, 20, 30]
D. None [50, 40, 30, 20, 10]
E. None None
D. None [50, 40, 30, 20, 10]
Which of the following will produce a sorted dictionary based on the score of the players
ordered from highest to lowest?
player_scores = {"Alice": 20, "Bob": 25, "Caroline": 21}
A. player scores.sort(reverse = True)
B. sorted(player scores.items(), key = key[1], reverse = True)
C. player scores.sort(key = key[1])
D. dict(sorted(player scores.items(), key = lambda k:k[0], reverse =
True))
E. dict(sorted(player scores.items(), key = lambda k:k[1], reverse =
True))
E. dict(sorted(player scores.items(), key = lambda k:k[1], reverse =
True))
Which of the following would generate a case-insensitive list of words containing "s"?
lattes = ["Pumpkin Spice", "Coconut", "Pistachio", "Vanilla"]
A. [for latte in lattes: if "s" in latte.lower(): latte]
B. [latte if "s" in latte.lower() for latte in lattes]
C. [latte for latte in lattes if "s" in latte]
D. [latte for latte in lattes if "s" in latte.lower()]
E. [latte for latte in lattes if "s" in latte.upper()]
D. [latte for latte in lattes if "s" in latte.lower()]
Consider the following code. What is the value of list1 after the following code executes?
list1 = []
list2 = [2, 1, 0, 4, 5]
i = 0
while i <= len(list2):
try:
c = 10 + list2[i]
list1.append(c)
except:
list1.append(0)
i += 1
A. [0, 0, 0, 0, 0]
B. [2, 1, 0, 4, 5]
C. [12, 11, 10, 14, 15]
D. [12, 11, 10, 14, 15, 0]
E. The program runs into a IndexError
D. [12, 11, 10, 14, 15, 0]
Assume the file Hello.txt does not exist before running this code. What is the value of the
variable data after the following code executes?
f = open("Hello.txt", "w")
f.write("Hello")
f.close()
f = open("Hello.txt", "w")
f.write("Hello")
f.write("World")
f.close()
f = open("Hello.txt", "r")
data = f.read()
f.close()
A. "Hello"
B. "HelloWorld"
C. "Hello\nWorld"
D. "HelloHelloHello"
E. "Hello\nHello\nWorld"
B. "HelloWorld"
What call to foo will not cause an AssertionError?
def foo(word1, word2):
assert type(word1) == str and type(word2) == str
assert len(word1) < len(word2)
return (word1 + " is better than " + word2)
A. foo("penguin", "bear")
B. foo(["seal"], "koala")
C. foo("tiger", "elephant")
D. foo("wolf", "frog")
E. foo("zebra", ["pig"])
C. foo("tiger", "elephant")
What line is printed last when the following code is executed?
my_list = [2, 0, 5, 0]
for item in my_list:
try:
print ("The number is:", item)
amount = 1 / item
print(amount)
except ZeroDivisionError as e:
print("help!")
A. The number is: 0 B. The number is: 5 C. ZeroDivisionError D. help!
D. help!
What is the last line of code that is executed in the following code?
def fun1(): # Line 1
print("Start: fun1") # Line 2
best = "fun1" + 2 # Line 3
print("End: fun1") # Line 4
def fun2(): # Line 5
print("Start: fun2") # Line 6
try: # Line 7
fun1() # Line 8
except: # Line 9
print("fun1 failed") # Line 10
print("End: fun2") # Line 11
try: # Line 12
fun2() # Line 13
except: # Line 14
print("fun2 failed") # Line 15
A. Line 10 B. Line 11 C. Line 14 D. Line 15
B. Line 11
What is the default delimiter between columns in a CSV file?
A. colon B. comma C. newline D. semicolon
B. comma
Which of the following is a valid JSON?
A. {"Messi":{"Stats":'91, 93, 85', "Country":null, "Club":'PSG'}}
B. {"Messi":{"Stats":"91, 93, 85", "Country":null, "Club":"PSG"}}
C. {"Messi":{"Stats", [91, 93, 85], "Country", null, "Club", "PSG"}}
D. {"Messi":{"Stats":[91, 93, 85], "Country":None, "Club":"PSG"}}
B. {"Messi":{"Stats":"91, 93, 85", "Country":null, "Club":"PSG"}}
Suppose double check exam.txt has the following content:
Wisc ID number bubbled in
Special code matches exam
Answers filled in completely
What is the output of the below code snippet?
f = open("double_check_exam.txt")
for line in f:
print(line[1])
f.close()
A. Wisc ID
B. Special code matches exam
C. i
p
n
D. ID
code
filled
E. Wi
Sp
An
C. i
p
n
What is the output of the following code snippet?
s = "Hello World!"
s = s.upper().split(" ")
print(s[-1][-1])
A. WORLD! B. D C. ! D. IndexError
C. !
What is the output of the following code snippet?
my_dict = {1: "One", 2: "Two", 3: "Four"}
my_dict["Zero"] = 0
print(1 in my_dict and 0 in my_dict)
A. True B. False C. None D. KeyError
B. False
For each question in this section, assume that the initial code executed is as follows:
vaccinations = [
{"iso": "ALB", "vacc": "Pfizer, Sinovac",
"vacc months": ["Jan", "Feb", "Mar", "May"],
"vacc counts": [549, 6728, 110015, 650001]},
{"iso": "FRO", "vacc": "Moderna, Pfizer",
"vacc months": ["Apr"], "vacc counts": [15531]},
{"iso": "VEN", "vacc": "Sputnik V",
"vacc months": ["Feb", "Apr", "May", "Jun"],
"vacc counts": [157, 10770, 316015, 620437]},
{"iso": "ZMB", "vacc": "Oxford",
"vacc months": ["Jun"], "vacc counts": [148304]}
]
16. What does the following evaluate to? vaccinations[0]["vacc"][1:3]
A. 6728, 110015 B. 6728, 110015, 650001 C. fi D. fiz
17. What does the following evaluate to?
vaccinations[-2]["vacc months"].index("May")
A. 3 B. 5 C. May D. 2 E. IndexError
18. What does the following evaluate to?
vaccinations[0]["vacc months"] + vaccinations[-1]["vacc months"]
A. `Jan, Feb, Mar, May, Jun'
B. [`Jan', `Feb', `Mar', `May', `Jun']
C. [`Jan', `Feb', `Mar', `May', [`Jun']]
D. [`Mar', `Apr', `Jun', `Jun']
16. fi
17. D. 2
18. B. [`Jan', `Feb', `Mar', `May', `Jun']
For each question in this section, assume that the initial code executed is as follows:
from collections import namedtuple
Student = namedtuple("Student", ["name", "grade", "ID"])
roster = [
Student("Michael", "B", 2),
Student("Sofia", "A", 3),
Student(ID = 6, name = "Alexander", grade = "AB"),
S tudent("Jill", "AB", 18)
]
24. What does roster[2].ID evaluate to?
A. 6 B. "6" C. "B" D. 3 E. "3"
25. What is the output of the following code snippet?
names = list()
for student in roster:
names.append(student.name)
names.sort(key = lambda n: len(n))
print(names)
A. [`Alexander', `Jill', `Michael', `Sofia']
B. [`Jill', `Sofia', `Michael', `Alexander']
C. [`Michael', `Sofia', `Alexander', `Jill']
D. [`Alexander', `Michael', `Sofia', `Jill']
26. Which of the following will result in an error?
A. roster.append(Student("Sarah", "A", 1))
B. roster[0] = Student("Alex", "AB", 4)
C. roster[0].ID = 20
D. roster.extend([Student("Cindy", "AB", 5), Student("Jack", "A", 7)])
E. None of the above
27. Which of the following sorts roster by decreasing order of IDs?
A. sorted(roster, key = lambda s:s.ID)
B. sorted(roster, lambda s:s["ID"])
C. sorted(roster, lambda s:s["ID"], reverse = True)
D. sorted(roster, key = lambda s:s.ID, reverse = True)
28. After executing the below code snippet, what does roster[1].name evaluate to?
import copy
new_roster1 = copy.copy(roster)
new_roster2 = roster
new_roster1[1] = Student("Rose", "B", 17)
new_roster2[1] = Student("Emily", "A", 42)
A. Emily B. Rose C. So a D. Michael
29. Which one of the following will create a list of student names with AB grade?
A. fkey:value for key, value in students.items() if student.grade ==
"AB"g
B. [student["name"] for student in roster if student.grade == "AB"]
C. [student.name for student in roster if student.grade == "AB"]
D. fstudent.name for student in roster if student.grade == "AB"g
24. A. 6
25. B. [`Jill', `Sofia', `Michael', `Alexander']
26. C. roster[0].ID = 20
27. D. sorted(roster, key = lambda s:s.ID, reverse = True)
28. A. Emily
29. C. [student.name for student in roster if student.grade == "AB"]
Which lines of code will get executed in the following code?
def b():
print("Start: B") # line 1
z = 100 / 0 # line 2
print("End: B") # line 3
def a():
print("Start: A") # line 4
try: # line 5
b() # line 6
except: # line 7
print("B failed") # line 8
print("End: A") # line 9
try: # line 10
a() # line 11
except: # line 12
print("A failed") # line 13
A. 1, 2, 3, 4, 5, 6, 9, 10, 11
B. 1, 2, 4, 5, 6, 7, 8, 9, 10, 11
C. 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
D. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
B. 1, 2, 4, 5, 6, 7, 8, 9, 10, 11
1. Using asserts is most useful for dealing with which category of errors?
A. syntax B. runtime C. semantic D. exceptional
2. What is true about frames?
A. there is always exactly one frame per function de nition
B. every object is associated with exactly one frame
C. all of the above
D. none of the above
1. C. semantic
2. D. none of the above