0% found this document useful (0 votes)
8 views13 pages

Spring 2024 Exam 3

This document is an exam for CS 1301 at Georgia Tech, covering topics such as file I/O, APIs, recursion, and object-oriented programming. It includes multiple-choice questions, short answer questions, and coding tasks that require students to demonstrate their understanding of Python programming concepts. The exam emphasizes academic integrity and adherence to the Georgia Tech Honor Code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views13 pages

Spring 2024 Exam 3

This document is an exam for CS 1301 at Georgia Tech, covering topics such as file I/O, APIs, recursion, and object-oriented programming. It includes multiple-choice questions, short answer questions, and coding tasks that require students to demonstrate their understanding of Python programming concepts. The exam emphasizes academic integrity and adherence to the Georgia Tech Honor Code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Page 1 / 13

CS 1301 Exam 3
Spring Semester 2024
Name (print clearly including your first and last name as it appears on your Buzzcard):
_______________________________________________________

Signature indicating you understand the Georgia Tech Honor Policy:


_______________________________________________________

GTID# (903000000, etc.):


_______________________________________________________

❖ Integrity: By taking this exam, you pledge that this is your work and you have neither given nor
received inappropriate help during the taking of this exam in compliance with the Academic
Honor Code of Georgia Tech. Do NOT sign nor take this exam if you do not agree with the honor
code.
❖ Signing and/or taking this exam signifies you are aware of and in accordance with the Academic
Honor Code of Georgia Tech and the Georgia Tech Code of Conduct.
❖ Academic Misconduct: Academic misconduct will not be tolerated. You are to uphold the honor
and integrity bestowed upon you by the Georgia Institute of Technology.
➢ Keep your eyes on your own paper.
➢ Do your best to prevent anyone else from seeing your work.
➢ Do NOT communicate with anyone other than a proctor for ANY reason in ANY
language in ANY manner.
➢ Follow directions given by the proctor(s).
➢ Stop all writing when told to stop. Continuing to write after the end of the exam is an
honor violation.
➢ Do not use notes, books, calculators, phones, laptops etc. during the exam.
➢ You are not allowed to leave the exam with your exam paper for any reason.
❖ Devices: If your cell phone, smartwatch, laptop, or similar item goes off during the exam, you
will lose 10 points on this exam. Turn all such devices off and put them away now. You cannot
have them on your desk.
❖ Extra paper is not allowed. If you have exhausted all space on this test, talk with your instructor.
❖ Pens/pencils and erasers are allowed. Do not share.
❖ All code must be in Python.
Page 2 / 13

PART I [34 pts] - File I/O, CSV Files, and APIs

1. Multiple Choice [16 pts] (4 pts each) For the following multiple
choice questions, indicate the best answer by selecting the
corresponding circle.

1a. Which of the following lines of code correctly opens a file called
"gruPlans.txt" in write mode?

o A. file = "gruPlans.txt".open()
o B. file = open("gruPlans.txt")
o C. file = open("gruPlans.txt", "write")
o D. file = open("gruPlans.txt", "w")
1b. When the following code is run, why does nothing get printed to
the shell?

letter = open("loveLetter.txt", "w")


letter.write("A Letter to Lucy from Minion Dave\n\n")
letter.write("I love you Lucy\n")
for i in range(100):
letter.write("<3\n")

file = open("loveLetter.txt", "r")


print(file.read())

o A. The file was opened in the wrong mode.


o B. The file was not closed after writing was finished.
o C. There is an extra newline character at the end of the file.
o D. A Runtime Error occurs before anything is printed.
Page 3 / 13

Use the following table from the file "minionPoints.csv" for problem
1c. You may assume that this is the entire file.

minions points pointMultiplier mentor

Bob 3 2 Gru

Dave 5 5 Lucy

Kevin 2 4 Gru

1c. Which of the following correctly sets the variable daveMentor to


the value "Gru"?

o A. myFile = open("minionPoints.csv", "r")


data = myFile.readline()
daveMentor = data[1].split(",")[3]
myFile.close()

o B. myFile = open("minionPoints.csv", "r")


header = myFile.readline()
myFile.readline()
myFile.readline()
data = myFile.readline()
daveMentor = data.strip().split(",")[3]
myFile.close()

o C. myFile = open("minionPoints.csv", "r")


data = myFile.read()
daveMentor = data.strip().split(",")[3]
myFile.close()

o D. myFile = open("minionPoints.csv", "w")


data = myFile.readlines()
daveMentor = data[1].strip().split(",")[3]
myFile.close()
Page 4 / 13

1d. What is the purpose of .json(), and what data type does it usually
return?

o A. It makes a request to an API endpoint, and it returns a


response object.

o B. It makes a request to an API endpoint, and it returns a


list or dictionary depending on the contents of the
endpoint.

o C. It converts data from an API into Python-readable code, and


it returns a list or dictionary depending on the contents
of the endpoint.

o D. It converts data from an API into Python-readable code, and


it returns a response object.
Page 5 / 13

2. API Tracing/Short Answer [18 pts] Use the data retrieved from the
mock Despicable Me API shown below to answer the following questions.
You should assume that there is more data than what is shown below.

Hint: The dictionary that is associated with the 'Weapons' key maps a
type of weapon to whether it works (True) or does not work (False).

villains = [
{ 'Name': 'Dr. Nefario',
'Occupation' : 'Evil Inventor',
'Enemies' : ['Vicious 5', 'Vector'],
'Weapons' : {'Dart Gun': False, 'Cookie Robots': True}
},
{ 'Name': 'Felonious Gru',
'Occupation' : 'Supervillain',
'Enemies' : ['Vector', 'Mr. Perkins', 'El Macho',
'Balthazar Bratt'],
'Weapons' : {'Freeze Ray': True, 'Cookie Robots': True,
'Jelly Gun': True, 'Lipstick Taser': True}
},

...
]

2a. [3 pts] What do the following lines of code print out?

for i in villains[0]['Enemies']:
if i in villains[1]['Enemies']:
print("duplicate!")
print(i)
Page 6 / 13

2b. [6 pts] Write a code snippet (not a function) that prints the
names of all the weapons that work. It is okay to print duplicate
weapons. Remember that there is more data than what is shown.
Example output:
Cookie Robots
Freeze Ray
Cookie Robots
...

2c. [9 pts] Write a code snippet (not a function) that creates a


dictionary called enemy_dict, mapping each enemy to a list of all
villains for which they are an enemy. Remember that there is more data
than what is shown.
Example output:
{'Vicious 5': ['Dr. Nefario'],
'Vector': ['Dr. Nefario', 'Felonious Gru'],
...}
Page 7 / 13

PART II [28 pts] - Recursion

3. Multiple Choice [8 pts] (4 pts each) For the following multiple


choice questions, indicate the best answer by selecting the
corresponding circle.

3a. Given the code snippet below, which of the following would NOT be
a good base case for the function power(x, n) which returns x raised
to the power of n? You can assume that n is positive.

def power(x, n):


if ______:
return 1
return x * power(x, n - 1)

print(power(2, 4)) # 2 * 2 * 2 * 2 * 1 = 16
print(power(5, 2)) # 5 * 5 * 1 = 25

o A. n <= 0
o B. n <= 1
o C. n == 0
o D. None of the above are valid base cases.
3b. What is the intended goal of recruitment()?

def recruitment(minions):
if minions == []:
return ""
return (minions[0] + ", " + recruitment(minions[1:]).strip(", "))

minions = ["Bob", "Otto", "Stuart", "Kevin"]


print(recruitment(minions))

o A. To return a tuple containing every name from minions.


o B. To return a string containing every name from minions.
o C. To print a string containing every name from minions.
o D. To print a tuple containing every name from minions.
Page 8 / 13

4. Recursion Tracing [8 pts] Show exactly what would be printed out


when the following code segment is executed. You may assume that this
code segment will not cause an error.

def traceMe(minionList):
if minionList == []:
return 0
else:
if minionList[0][1] == "king":
print("king bob")
minionList.append(("dave", "banana"))
return 5 + traceMe(minionList[1:])
elif minionList[0][0] == "bob":
print(minionList[0][1])
return 1 + traceMe(minionList[1:])
else:
if minionList[0][1] == "mid":
print("loves")
else:
print(minionList[0][1])
return 0 + traceMe(minionList[1:])

minionList = [("kevin", "formal"), ("bob", "king"),


("stuart", "mid"), ("bob", "absolutely cute")]
print(traceMe(minionList))
Page 9 / 13

5. Recursion Coding [12 pts]


Gru is trying to figure out which villain to catch next. Write a
function called chosenVillain() that takes in one parameter: a list of
votes for villain names. Your function should return a dictionary that
holds the name of each villain in the list (str) mapped to how many
votes they received (int).

Note: You must use recursion for this function to receive credit. Code
that uses any loops will receive a 0.

Example Output #1:


>>> chosenVillain(["El Macho", "Vector", "El Macho", "Balthazar Bratt"])
{'Balthazar Bratt': 1, 'El Macho': 2, 'Vector': 1}

Example Output #2:


>>> chosenVillain(["Scarlet Overkill", "Scarlet Overkill", "Vector"])
{'Vector': 1, 'Scarlet Overkill': 2}
Page 10 / 13

PART III [38 pts] - OBJECT ORIENTED PROGRAMMING

6. Multiple Choice [8 pts] (4 pts each) For the following multiple


choice questions, indicate the best answer by selecting the
corresponding circle.

6a. Which of the following statements is False?

o A. Comparison dunder methods are not required for every class.


o B. If gru and scarlet, two objects of the class DespicableMe,
have the same values for all attributes, gru == scarlet will
always return True.

o C. You are allowed to create two objects that have the same
values for all attributes.

o D. If there is no __str__() method, the memory location is


outputted when print() is called on an object.

o E. None of the above are False.


6b. Which of the following will create an instance of the Minion class
with its favorite_villain attribute set to "Gru"?

class Minion:
def __init__(self, name, favorite_villain = "Gru"):
self.name = name
self.favorite_villain = "Scarlet Overkill"

o A. bob = Minion("Bob", "Gru")


o B. kevin = Minion("Kevin")
o C. stuart = Minion("Stuart", "El-Macho")
o D. None of the above
o E. Both A and B
Page 11 / 13

7. OOP Tracing [10 pts] Write down exactly what will be printed when
the following code is executed.
class Minion:
def __init__(self, name, eyes, favLeader, friends = {}):
self.name = name
self.eyes = eyes
self.favLeader = "Gru"
self.friends = friends
def __lt__(self, other):
return len(self.friends) < len(other.friends)
def failedLeader(self, leader, partner):
if leader != self.favLeader:
print("That's not our leader!")
for friend, isFriend in self.friends.items():
if friend in partner.friends:
print(friend)
self.friends[friend] = False
def mission(self):
totalFriends = 2
if self.eyes == 2:
print("Only if it's Kevin!")
for friend, isFriend in self.friends.items():
if isFriend == True:
totalFriends += 1
if totalFriends < 3:
return "Lol no <3"
stuart = Minion("Stuart", 1, "Scarlet", {"Bob": True, "Dave": False})
kevin = Minion("Kevin", 2, "Gru", {"Dave": True, "Carl": False})
stuart.failedLeader("Scarlet", kevin)
print(stuart < kevin)
print(kevin.mission())
Page 12 / 13

8. OOP Coding [20 pts] For this section, you will be writing 2 methods
for the MinionHunt class. Each method description will be followed by
test cases. You are not writing the entire class, just the appropriate
methods.
class MinionHunt:
def __init__(self, name, bananas, obs = []):
self.name = name # str: the name of the minion
self.bananas = bananas # int: the number of bananas it has collected
self.obstacles = obs # list: the obstacles it is able to avoid
self.isAwake = True # bool: if it is awake or not
Method 1 [8 pts]:
Write a method that overrides the default greater than operator (>). A
MinionHunt object is greater than another MinionHunt object if the
bananas collected by the first minion are strictly greater than the
bananas collected by the second minion and the first minion has more
obstacles in their obstacles list than the second minion.
Example Output:
>>> minion1 = MinionHunt("Dave", 4, ["Gru", "apple", "slide", "Clive"])
>>> minion2 = MinionHunt("Kevin", 5, ["El-Macho", "apple", "broom"])
>>> minion3 = MinionHunt("Bob", 3)
>>> minion1 > minion3
True
>>> minion2 > minion1
False
Page 13 / 13

Method 2 [12 pts]:


Write a method called bananaHunt() that takes in two additional
parameters: obstacleList (list), which is the list of obstacles the
minion will face in its hunt, and target (int), which is the number of
bananas it has to collect. For every obstacle in obstacleList that is
one the minion can avoid, the function should increment its banana
attribute by one. However, if the minion encounters three obstacles
that it cannot avoid, it falls asleep (set isAwake to False) and the
hunt ends.

If the minion's bananas attribute is greater than or equal to the


target at the end of the hunt, the method should return the total
bananas collected as the string, "Kampai! {bananas} bananas".
Otherwise return the string "Bi do, {name} want banana :(".
Example Output:
>>> minion = MinionHunt("Bob", 15, ["Gru", "slide", "violin"])
>>> minion.bananaHunt(["Gru", "broom", "slide", "violin"], 17)
'Kampai! 18 bananas'
>>> minion = MinionHunt("Kevin", 12, ["El-Macho", "piano", "hat"])
>>> minion.bananaHunt(["Scarlet", "piano", "flute", "chemical"], 15)
'Bi do, Kevin want banana :('
>>> minion.bananas
13
>>> minion.isAwake
False

You might also like