Download CS 106A Practice Final Examination and more Exams Nursing in PDF only on Docsity!
CS 106A Practice Final Examination
Course: CS 106A — Programming Methodology
Exam Type: Practice Final Examination
Total Points: 150
Suggested Time: 180 minutes
Language: Python 3
Coverage: Comprehensive, weighted toward post-midterm material
This exam follows the current CS 106A final style: short-answer questions, functions using
lists/tuples, strings, dictionaries, file reading and split(), lambda-based sorting,
comprehensions, and classes. Stanford’s exam reference identifies these as central final-exam
tools, while noting that the final is cumulative and weighted toward post-midterm
material.web.stanford+
Table of Contents
1. Instructions
2. Problem 1 — Short Answer
3. Problem 2 — One-Line Expressions
4. Problem 3 — Strings
5. Problem 4 — Lists and Tuples
6. Problem 5 — Dictionaries
7. Problem 6 — Nested Dictionaries
8. Problem 7 — File Processing
9. Problem 8 — Classes
10. Reference Solutions
Instructions
Write complete, syntactically valid Python 3 code.
Unless otherwise stated, write functions that return values rather than print them.
Do not modify an input collection unless the problem explicitly asks for in-place
modification.
You may define helper functions.
Point values indicate approximate suggested time.
Problem 1 — Short Answer
20 points
Evaluate each code fragment independently.
Part A — 5 points
python print (31 // 7, 31 % 7)
Part B — 5 points
python s = "university" print (s[4:9] + s[-2])
Part C — 5 points
python words = ["pear", "pineapple", "plum"] print (sorted(words, key=len))
Part D — 5 points
python nums = [1, 4, 7, 10] print ([n + 5 for n in nums if n % 2 == 0])
Problem 2 — One-Line Expressions
15 points
For each part, write one line using a comprehension, map(), sorted(), min(), or max().
Part A — 5 points
Given:
python nums = [5, 10, 15, 20]
write an expression that produces:
Problem 4 — Lists and Tuples
20 points
A list contains tuples in this form:
python (name, score)
Write a function:
python def top_scores(results, n):
The function returns a new list containing the names of the n students with the highest scores,
sorted from highest score to lowest score.
If two students have the same score, preserve their original relative order.
You may assume n is no larger than the number of students.
Example:
python results = [("Ada", 88), ("Bo", 95), ("Cy", 88), ("Dee", 91)]
top_scores(results, 3)
should return:
python ["Bo", "Dee", "Ada"]
Problem 5 — Dictionaries
20 points
Write a function:
python def invert_counts(counts):
The parameter counts is a dictionary mapping words to integer counts.
Return a new dictionary mapping each count to a list of all words with that count.
Example:
python counts = {"apple": 2, "banana": 1, "cherry": 2} invert_counts(counts)
should return:
python {2: ["apple", "cherry"], 1: ["banana"]}
Problem 6 — Nested Dictionaries
25 points
Write a function:
python def add_reading(data, sensor, date, value):
The parameter data is a dictionary mapping sensor names to dictionaries. Each inner dictionary
maps a date string to the most recent reading for that sensor on that date.
Your function should store value as the most recent reading.
If the sensor does not exist, create it.
If the date does not exist for that sensor, create it.
If the date already exists, replace the old value with value.
Modify data in place.
Return data.
Example:
python data = { "temp1": {"2026-10-27": 70} }
add_reading(data, "temp1", "2026-10-27", 75) add_reading(data, "temp2", "2026-10-27", 68)
After the calls:
python { "temp1": {"2026-10-27": 75}, "temp2": {"2026-10-27": 68} }
The constructor takes no parameters and creates an instance variable count initialized to
increment() increases count by 1 and returns the new count.
increment_by(amount) increases count by amount and returns the new count.
reset() sets count back to 0 and returns 0.
get_count() returns the current count.
Example:
python c = Counter() c.increment() # returns 1 c.increment_by(4) # returns 5 c.reset() # returns 0 c.get_count() # returns 0
Reference Solutions
Problem 1 — Short Answer
Part A
text 4 3
Integer division gives 31//7=431 // 7 = 431//7=4, and the remainder gives 31%7=331 % 7 =
Part B
text ersityt
s[4:9] is "ersit", and s[-2] is "t".
Part C
text ['plum', 'pear', 'pineapple']
The list is sorted by string length in ascending order.
Part D
text [9, 15]
Only even values, 4 and 10 , are kept; each has 5 added.
These mirror CS 106A final reference operations such as integer division, string slicing,
sorted() with key, and comprehensions.web.stanford
Problem 2 — One-Line Expressions
Part A
python [n * 2 for n in nums]
Part B
python [name[0].upper() for name in names]
Part C
python sorted(products, key= lambda product: product[1], reverse=True)
Why these work: Comprehensions transform or filter sequences, and sorted(...,
key=lambda product: product[1], reverse=True) orders tuples by their second field in
descending order. These are standard CS 106A final expression patterns.web.stanford
Problem 3 — Swap Case
python def swap_case(s): result = "" for ch in s: if ch.isupper(): result += ch.lower() elif ch.islower(): result += ch.upper() else : result += ch return result
def add_reading(data, sensor, date, value): if sensor not in data: data[sensor] = {}
data[sensor][date] = value return data
Why this works: The function first ensures the outer sensor key exists, then assigns the new
value to the date key. Assignment naturally replaces any previous value, as required. This
follows the CS 106A nested-dictionary update pattern.web.stanford
Problem 7 — Item Totals
python def item_totals(filename): totals = {}
with open(filename, "r") as f: for line in f: parts = line.strip().split(",")
item = parts[1] quantity = int(parts[2])
if item not in totals: totals[item] = 0
totals[item] += quantity
return totals
Why this works: Each line is stripped and split at commas. The item and quantity fields are
extracted, the quantity is converted to an integer, and the function accumulates each item’s total.
This combines CS 106A file reading, split(","), type conversion, and dictionary
counting.web.stanford+
Problem 8 — Counter Class
python class Counter: def init(self): self.count = 0
def increment(self): self.count += 1 return self.count
def increment_by(self, amount): self.count += amount return self.count
def reset(self): self.count = 0 return self.count
def get_count(self): return self.count
Why this works: The constructor initializes count to 0. Each method updates or reads the
instance variable as specified and returns the required value. Class construction, instance
variables, and methods are core CS 106A final topics