Docsity

CS 106A Practice Final Examination, Exams of Nursing

Toggle sidebar
bg1
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.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

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 (29 // 6, 29 % 6)

Part B — 5 points

python s = "methodology" print (s[3:8] + s[0])

Part C — 5 points

python words = ["kiwi", "watermelon", "fig"] print (sorted(words, key=len, reverse=True))

Part D — 5 points

python nums = [2, 5, 8, 11] print ([n * n for n in nums if n % 2 == 1])

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 = [3, 6, 9, 12]

write an expression that produces:

20 points

A list contains tuples in this form:

python (title, pages, rating)

Write a function:

python def highly_rated(books, min_rating):

The function returns a new list containing only books whose rating is at least min_rating, sorted

from shortest to longest by page count.

If two books have the same number of pages, preserve their original relative order.

Example:

python books = [ ("Book A", 400, 4.5), ("Book B", 250, 4.8), ("Book C", 300, 4.2) ]

highly_rated(books, 4.2)

should return:

python [ ("Book B", 250, 4.8), ("Book C", 300, 4.2), ("Book A", 400, 4.5) ]

Problem 5 — Dictionaries

20 points

Write a function:

python def count_lengths(words):

The parameter words is a list of non-empty strings.

Return a dictionary mapping each distinct word length to the number of words in the list with

that length.

Example:

python count_lengths(["cat", "dog", "bird", "fish", "elephant"])

should return:

python {3: 2, 4: 2, 8: 1}

Problem 6 — Nested Dictionaries

25 points

Write a function:

python def add_donation(data, donor, cause, amount):

The parameter data is a dictionary mapping donor names to dictionaries. Each inner dictionary

maps a cause name to the total amount donated to that cause.

Your function should add amount to the appropriate total.

 If the donor does not exist, create it.

 If the cause does not exist for that donor, create it with value 0.

 Modify data in place.

 Return data.

Example:

python data = { "Ada": {"education": 100} }

add_donation(data, "Ada", "education", 50) add_donation(data, "Bo", "health", 75)

After the calls:

python { "Ada": {"education": 150},

20 points

Write a class called Playlist with the following behavior:

 The constructor takes name and stores it as an instance variable.

 The constructor also creates an empty list called songs.

 add_song(title) adds a song title to the playlist.

 has_song(title) returns True if the title is already in the playlist; otherwise it returns

False.

 remove_song(title) removes the first occurrence of the title if it exists and returns

True; if it does not exist, returns False.

 song_count() returns the number of songs in the playlist.

Example:

python p = Playlist("Favorites") p.add_song("Song A") p.add_song("Song B") p.has_song("Song A") # returns True p.remove_song("Song A") # returns True p.song_count() # returns 1

Reference Solutions

Problem 1 — Short Answer

Part A

text 4 5

Integer division gives 29//6=429 // 6 = 429//6=4, and the remainder gives 29%6=529 % 6 =

Part B

text hodolm

s[3:8] is "hodol", and s[0] is "m".

Part C

text ['watermelon', 'kiwi', 'fig']

The list is sorted by length from longest to shortest.

Part D

text [25, 121]

Only odd values, 5 and 11 , are kept and squared.

These question types align with 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 + "!" for name in names]

Part C

python sorted(people, key= lambda person: person[2])

Why these work: Comprehensions transform or filter sequences, and sorted(...,

key=lambda person: person[2]) orders tuples by their third field in ascending order. These

are standard CS 106A final expression patterns.web.stanford

Problem 3 — Count Uppercase

python def count_uppercase(s): count = 0 for ch in s:

python def add_donation(data, donor, cause, amount): if donor not in data: data[donor] = {}

if cause not in data[donor]: data[donor][cause] = 0

data[donor][cause] += amount return data

Why this works: The function safely creates the missing outer donor key and inner cause key

before accumulating the donation. This is the standard CS 106A nested-dictionary update

pattern.web.stanford

Problem 7 — Customer Totals

python def customer_totals(filename): totals = {}

with open(filename, "r") as f: for line in f: parts = line.strip().split(",")

customer = parts[0] quantity = int(parts[2])

if customer not in totals: totals[customer] = 0

totals[customer] += quantity

return totals

Why this works: Each line is stripped and split at commas. The customer and quantity fields are

extracted, the quantity is converted to an integer, and the function accumulates each customer’s

total. This combines CS 106A file reading, split(","), type conversion, and dictionary

counting.web.stanford+

Problem 8 — Playlist Class

python class Playlist: def init(self, name): self.name = name self.songs = []

def add_song(self, title): self.songs.append(title)

def has_song(self, title): return title in self.songs

def remove_song(self, title): if title in self.songs: self.songs.remove(title) return True return False

def song_count(self): return len(self.songs)

Why this works: The constructor stores the playlist name and initializes an empty list. The

methods add, search for, remove, and count songs. Class construction, instance variables, lists,

and methods are core CS 106A final topics.