Mock midterm: the answers

Think about each question first, then open the answer. Next to each wrong option: the mistake that leads to it.

L1 · 2 pt

Slicing a list

Choose the value of each expression. Choose crashes if the expression stops the program.

1  closes = [190.5, 187.2, 193.8, 185.1, 191.4, 198.6]
Show the answer
  • closes[-2:] → [191.4, 198.6]
  • closes[1:4] → [187.2, 193.8, 185.1]
  • closes[6] → crashes
  • closes[::2] → [190.5, 193.8, 191.4]

Key idea: Start and stop are cuts between the boxes; the stop is not included; a too-big index crashes, a too-big slice does not.

M5 · 3 pt

Is this output plausible?

A colleague computes the average daily return of a price series, in percent. The program prints 2.5. Answer the three questions.

1  prices = [100.0, 110.0, 99.0, 108.9]
2  total = 0.0
3  for i in range(1, len(prices)):
4      change = prices[i] / prices[i - 1] - 1
5      total += change
6  average = total / len(prices)
7  print(round(average * 100, 1))
Show the answer
  • The daily returns are +10%, -10% and +10%. Is 2.5 a plausible average? → No
  • Why? → It divides by the number of prices (4), not the number of returns (3)
  • Which line causes it? → Line 6

Key idea: Do a rough check first: +10, -10, +10 average about 3.3, so 2.5 is too low. 3 returns, not 4 prices.

Also in the session 7 review: Item 2

L6 · 2 pt

From a line of text to fields

One line read from a CSV file is split into fields. Choose the value of each expression.

1  line = "NESN,Nestlé,4,102.30\n"
2  parts = line.strip().split(",")
Show the answer
  • len(parts) → 4
  • parts[2] * 2 → '44'
  • float(parts[3]) → 102.3
  • parts[0] + parts[2] → 'NESN4'

Key idea: split gives STRINGS: "4" * 2 is "44". Convert with int()/float() before computing.

M4 · 4 pt

Read a whole program: trades in, positions out

Read the file trades.csv and the program, then answer the four questions.

File trades.csv

ticker,qty,price
AAPL,10,190.50
NESN,,102.30
VOO,2,512.00
AAPL,-3,191.00
 1  def load(path):
 2      trades = []
 3      with open(path, encoding="utf-8") as f:
 4          f.readline()
 5          for line in f:
 6              ticker, qty, price = line.strip().split(",")
 7              try:
 8                  trades.append((ticker, int(qty), float(price)))
 9              except ValueError:
10                  print("skipped", ticker)
11      return trades
12  
13  def net(trades):
14      shares = {}
15      for ticker, qty, price in trades:
16          shares[ticker] = shares.get(ticker, 0) + qty
17      return shares
18  
19  trades = load("trades.csv")
20  result = net(trades)
21  print(len(trades), result)
Show the answer
  • Which line skips the header? → Line 4
  • What is the first line on the screen? → skipped NESN
  • How many trades does load return? → 3
  • result["AAPL"] → 7

Key idea: Read the file first, then follow one row through the program. NESN has no qty: int("") raises, except prints, the loop goes on.

Also in the session 7 review: Item 11

K3 · 1 pt

Where does a relative path point?

Li's working directory is /Users/li/dsap/week-06. Her script runs open("../data/prices.csv"). Which file does Python try to open?

Show the answer
  • ✓ /Users/li/dsap/data/prices.csv
  • ✗ /Users/li/dsap/week-06/data/prices.csv ignores the ..
  • ✗ /data/prices.csv reads the relative path as absolute
  • ✗ /Users/li/data/prices.csv goes up two folders instead of one

Key idea: A relative path starts in the working directory; .. goes up ONE folder.

L4 · 2 pt

Which line breaks the brief?

Brief: count the positions worth more than 1000 CHF. The program runs without an error. Which line, if any, breaks the brief?

1  values = [1905.0, 409.2, 1024.0, 1000.0]
2  count = 0
3  for v in values:
4      if v >= 1000:
5          count += 1
6  print(count)
Show the answer
  • ✓ Line 4
  • ✗ Line 2 thinks count must start at 1
  • ✗ Line 5 thinks += is wrong for counting
  • ✗ No line: the program follows the brief does not check the boundary value 1000.0

Key idea: Brief says MORE THAN: >= also counts 1000.0. Always test the boundary value.

Also in the session 7 review: Item 3

M1 · 3 pt

print is not return

What appears on the screen? (Each option shows the lines in order; then it crashes means the program stops with an error after those lines.)

1  def value(shares, price):
2      print(shares * price)
3  
4  total = value(10, 190.5) + value(4, 102.3)
5  print(total)
Show the answer
  • ✓
    1905.0
    409.2
    then it crashes
  • ✗ 2314.2 thinks print gives back a value
  • ✗
    1905.0
    409.2
    2314.2
    thinks the printed values are added
  • ✗
    1905.0
    409.2
    None
    thinks None + None is None

Key idea: print shows, return gives back. A function with no return gives None, and None + None crashes AFTER both prints.

Also in the session 7 review: Item 6

M2 · 2 pt

Won't start, or crashes?

What appears on the screen? Remember: Python reads the whole file before it runs any line.

1  print("start")
2  total = 0
3  for p in [190.5, 102.3]
4      total += p
5  print(total)
Show the answer
  • ✓ Nothing: the program does not start
  • ✗
    start
    then it crashes
    thinks the lines before the error run first
  • ✗
    start
    292.8
    does not see the missing colon
  • ✗ start thinks Python stops quietly at the bad line

Key idea: Python reads the whole file first: a missing : means NOTHING runs, not even line 1. A crash happens later, after earlier lines printed.

Also in the session 7 review: Item 4

M6 · 3 pt

Only one output is possible

Brief: read trades.csv and print how many trades are buys (quantity above 0) and how many shares were bought in total. Four colleagues wrote four programs and got the four outputs below. Only one output can come from a program that follows the brief. Which one?

File trades.csv

ticker,qty
AAPL,10
NESN,-4
VOO,2
AAPL,-3
MSFT,5
Show the answer
  • ✓ 3 buys, 17 shares
  • ✗ 5 buys, 10 shares every trade counted: there is no check on the sign
  • ✗ 3 buys, 5 shares only the last buy survives: the total is reset inside the loop
  • ✗ 5 buys, 24 shares sells counted as buys: abs() turns -4 into 4

Key idea: Compute the brief by hand from the file (10 + 2 + 5 = 17, 3 buys), then match each wrong output to its bug.

Also in the session 7 review: Item 12

K4 · 1 pt

"w" and "a"

The program writes to log.txt several times. What number does it print?

 1  with open("log.txt", "w") as f:
 2      f.write("AAPL\n")
 3  for t in ["NESN", "VOO"]:
 4      with open("log.txt", "a") as f:
 5          f.write(t + "\n")
 6  with open("log.txt", "w") as f:
 7      f.write("MSFT\n")
 8  with open("log.txt", "a") as f:
 9      f.write("TSLA\n")
10  print(len(open("log.txt").read().splitlines()))
Show the answer
  • ✓ 2
  • Common wrong answers: 5 (thinks w also appends), 1, 3

Key idea: "w" empties the file the moment it opens it; "a" adds at the end. Count only what survives the last "w".