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, with emphasis on post-midterm material
This practice final emphasizes the post-midterm CS 106A topics: file reading and split(),
dictionaries and counting algorithms, nested dictionaries, tuples, comprehensions, lambda
functions, custom sorting, and classes. Stanford’s final-preparation materials identify these as the
principal areas beyond the midterm, while noting that the exam remains
cumulative.web.stanford+
Table of Contents
1. Instructions
2. Problem 1 — Short Answer
3. Problem 2 — Warm-Up Functions
4. Problem 3 — Strings
5. Problem 4 — Lists, Tuples, and Sorting
6. Problem 5 — Dictionaries
7. Problem 6 — Nested Dictionaries
8. Problem 7 — File Processing Capstone
9. Problem 8 — Classes
10. Reference Solutions
Instructions
Write complete, syntactically valid Python 3 code.
Unless a problem says otherwise, 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 expression or code fragment independently.
Part A — 5 points python print (17 // 5, 17 % 5) Part B — 5 points python s = "Stanford" print (s[3:] + s[0]) Part C — 5 points python nums = [1, 2, 3, 4] print ([n * 10 for n in nums if n % 2 == 1]) Part D — 5 points python movies = [("A", 100), ("B", 140), ("C", 120)] movies.sort(key= lambda movie: movie[1], reverse=True) print (movies[0][0]) Problem 2 — Warm-Up Functions
15 points
Write each function.
Part A — 5 points
Write:
python def classify(n):
python def initials(s):
The parameter s is a string containing one or more words separated by one or more spaces.
Return a string containing the uppercase first letter of each word, with no spaces.
Example:
python initials("ada lovelace") # returns "AL" initials(" grace brewster hopper") # returns "GBH"
You may assume every word begins with a letter.
Problem 4 — Lists, Tuples, and Sorting
20 points
A list of tuples stores information about books:
python (title, pages, rating)
For example:
python books = [ ("Book A", 300, 4.2), ("Book B", 250, 4.8), ("Book C", 400, 4.2) ]
Write a function:
python def top_books(books, min_rating):
The function returns a new list containing only books whose rating is at least min_rating, sorted
from longest to shortest by page count.
If two books have the same number of pages, preserve their original relative order.
Example:
python top_books(books, 4.2)
should return:
python [ ("Book C", 400, 4.2), ("Book A", 300, 4.2), ("Book B", 250, 4.8) ] Problem 5 — Dictionaries
20 points
Write a function:
python def total_length(names):
The parameter names is a dictionary mapping each person’s name to a list of that person’s
friends’ names.
Return the total number of characters in all friend names across the entire dictionary.
Example:
python names = { "Ada": ["Bo", "Cy"], "Bo": ["Ada"], "Cy": [] }
total_length(names) should return 8 , because "Bo" has length 2, "Cy" has length 2, and
"Ada" has length 3, for a total of 2+2+3=72 + 2 + 3 = 72+2+3=7. Wait—recount carefully before
answering.
Problem 6 — Nested Dictionaries
25 points
Write a function:
python def add_observation(data, city, date, temperature):
python def event_totals(filename):
The function reads the file and returns a nested dictionary mapping each year to a dictionary
mapping each city to the total event count for that city during that year.
For the example above, the returned dictionary should be:
python { "2026": { "Stanford": 8, "Berkeley": 6 } }
Rules:
The date format is always YYYY-MM-DD.
The count is always the third comma-separated field.
Convert the count to an integer before adding it.
Return the dictionary; do not print it.
Problem 8 — Classes
20 points
Write a class called LibraryBook with the following behavior:
The constructor takes title, author, and pages, and stores all three as instance
variables.
is_long() returns True if the book has more than 300 pages; otherwise it returns False.
add_pages(extra) adds extra pages to the book and returns the new page count.
summary() returns a string in exactly this format:
text Title by Author (pages pages)
Example:
python book = LibraryBook("Python Basics", "Ada", 250) book.is_long() # returns False book.add_pages(100) # returns 350 book.is_long() # returns True book.summary() # returns "Python Basics by Ada (350 pages)"
Reference Solutions Problem 1 — Short Answer Part A text 3 2
Integer division gives 17//5=317 // 5 = 317//5=3, and the remainder gives 17%5=217 % 5 =
Part B text fordS
s[3:] is "ford", and s[0] is "S".
Part C text [10, 30]
Only odd values, 1 and 3 , are kept; each is multiplied by 10.
Part D text B
The movies are sorted by page count in descending order, so ("B", 140) comes first. Its title is
"B".
These short-answer patterns align with CS 106A final reference topics such as integer division,
string slicing, comprehensions, lambda expressions, and custom sorting.stanford+
Problem 2 — Warm-Up Functions
for ch in s: if take_next and ch.isalpha(): result += ch.upper() take_next = False elif ch.isspace(): take_next = True return result
Why this works: The Boolean flag becomes True after whitespace, so the next alphabetic
character is capitalized and added to the result. Extra spaces are handled because the flag remains
True until a letter is found. This uses isalpha(), isspace(), and upper(), all listed in the CS
106A exam reference.stanford
Problem 4 — Books, Tuples, and Sorting python def top_books(books, min_rating): selected = [] for book in books: if book[2] >= min_rating: selected.append(book) return sorted(selected, key= lambda book: book[1], reverse=True)
Why this works: The function first filters books by rating, then sorts the resulting list by the
page-count field, book[1], in descending order. sorted() returns a new list, and Python’s stable
sort preserves the original order for equal page counts. Custom sorting with key=lambda is a
core CS 106A final skill.stanford+
Problem 5 — Dictionary Total Length python def total_length(names): total = 0 for friends in names.values(): for friend in friends: total += len(friend) return total
Why this works: The outer loop visits each list of friends, and the inner loop visits each friend
name. Adding len(friend) accumulates the total number of characters.
For the example, the friend names are "Bo", "Cy", and "Ada", so the correct return value is:
text 7
The problem statement’s preliminary count of 8 was incorrect; the verified total is 7. Dictionary
iteration with values() and nested-list traversal are standard CS 106A final topics.stanford+
Problem 6 — Nested Dictionaries python def add_observation(data, city, date, temperature): if city not in data: data[city] = {} if date not in data[city]: data[city][date] = temperature elif temperature > data[city][date]: data[city][date] = temperature return data
Why this works: The function first ensures the outer city key exists, then ensures the inner date
key exists. If a temperature already exists, it keeps the larger value. This follows the CS 106A
nested-dictionary pattern of safely creating missing outer and inner keys before updating
data.web.stanford+
Problem 7 — File Processing Capstone python def event_totals(filename): result = {} with open(filename, "r") as f: for line in f: parts = line.strip().split(",") city = parts[0] date = parts[1] count = int(parts[2]) year = date.split("-")[0] if year not in result: result[year] = {} if city not in result[year]: