Data Science and Advanced Programming · Midterm

Midterm review: the workshop tasks

The core tasks of sessions 2–5, with their answers.

The midterm asks the same kind of questions as these tasks: read code, then say what it prints, which line is wrong, or which error it raises. For each task, answer on paper first, without running anything. Then open the answer. If you were wrong, run the code in your workspace and find the line where your prediction and Python part ways.

Session 2: values, names, types

Task 1 · names are labels, not formulas

On paper, fill in a table: after each line, what is every name, and what is its type? Then predict what the print shows. Question: price changed on line 5. Why did old_price and value not change with it?

price = 102.3
old_price = price
shares = 4
value = shares * price
price = 105.0
shares += 6
print(old_price, price, shares, value)

What does the print show?

Show the answer

102.3 105.0 10 409.2

Assignment binds a name to a value once. old_price got the value 102.3, not "whatever price is". value was computed on line 4 with the numbers of that moment; nothing is ever recomputed.

Task 2 · the money disappeared

Buying shares at the market price does not make you richer or poorer: shares × price + cash is the same before and after a purchase. This code runs without an error, but it breaks that rule. Find the line, say in one sentence what it does wrong, and fix it.

shares = 4
price = 102.3
cash = 1000.0
wealth_before = shares * price + cash

shares = shares + 6
cash = cash - shares * price

wealth_after = shares * price + cash
print(wealth_before, wealth_after)

Which line breaks the rule?

Show the answer

cash = cash - shares * price

shares = 4
price = 102.3
cash = 1000.0
wealth_before = shares * price + cash

bought = 6
shares = shares + bought
cash = cash - bought * price

wealth_after = shares * price + cash
print(wealth_before, wealth_after, abs(wealth_after - wealth_before) < 0.01)

The buggy version prints 1409.2 1000.0. Cash is charged AFTER shares was raised to 10, so all 10 shares are paid for, not the 6 bought. The order of lines is state. Charge for what you buy, and check the rule with a tolerance, not ==.

Task 6 · a purchase with a rule

You hold 2 VOO at 512.00 CHF and have 3000.00 CHF cash. Rule: spend at most 40 % of your cash, and buy whole shares only. Write the lines that work out how many shares you buy, update shares and cash, check that wealth did not change (with a tolerance, not ==), and print one line with an f-string.

ticker = "VOO"
shares = 2
price = 512.0
cash = 3000.0

# your code here
Show the solution
ticker = "VOO"
shares = 2
price = 512.0
cash = 3000.0

wealth_before = shares * price + cash
bought = int(cash * 0.4 // price)
shares += bought
cash -= bought * price
print(f"{ticker}: bought {bought}, now {shares} shares, cash {cash:.2f} CHF")
print(abs(shares * price + cash - wealth_before) < 0.01)

It prints:

VOO: bought 2, now 4 shares, cash 1976.00 CHF
True

40 % of 3000 is 1200; 1200 // 512 is 2 whole shares. Update shares and cash from the same bought, so the invariant holds. int() turns the float result of // into a whole number for printing.

Task 7 · the same purchase in cents

Floats cannot store most prices exactly. Money is safer as whole cents. Redo Task 6 with integers only: 512.00 CHF is 51200 cents, 3000.00 CHF is 300000 cents. At the end, print the cash as CHF, built from // and % (no division, no float).

shares = 2
price_c = 51200
cash_c = 300000

# your code here
Show the solution
shares = 2
price_c = 51200
cash_c = 300000

bought = cash_c * 40 // 100 // price_c
shares += bought
cash_c -= bought * price_c
print(f"CHF {cash_c // 100}.{cash_c % 100:02d}")

It prints:

CHF 1976.00

cash_c // 100 is the francs, cash_c % 100 the cents; :02d pads 0 to "00". Everything stays an int, so nothing is ever rounded. Choosing the representation of the data is a decision the programmer makes.

Session 3: lists, loops, decisions, dicts

The data these tasks start from
tickers = ["AAPL", "NESN", "VOO"]
shares = [10, 4, 2]
price = {"AAPL": 190.5, "NESN": 102.3, "VOO": 512.0}
closes = [190.5, 187.2, 193.8, 185.1, 191.4, 198.6, 194.0]   # AAPL, day 0 to day 6

Task 1 · slices

On paper, predict what each line prints. Then run and compare. Remember: positions start at 0, the stop is not included, and a slice never crashes.

print(closes[1:4])
print(closes[::3])
print(closes[::-1][:2])
print(closes[5:100])
print(tickers[3:])

What is closes[::-1][:2]?

Show the answer

[194.0, 198.6]

[1:4] is positions 1, 2, 3. [::3] takes every third item from the start. [::-1] reverses, then [:2] keeps the first two of the reversed list: the last two days, newest first. [5:100] stops at the end instead of crashing. tickers[3:] is empty, while tickers[3] would be an IndexError.

Task 2 · a copy, or a second name?

Predict both lines. Then say in one sentence what backup = shares creates, and what shares.copy() creates.

backup = shares
backup.append(5)
print(shares)

shares = [10, 4, 2]
backup = shares.copy()
backup[1] = 10
print(shares, backup)

What does Task 2a print?

Show the answer

[10, 4, 2, 5]

backup = shares puts a second name on the SAME list, so append through one name shows through the other. shares.copy() builds a NEW list; changing the copy leaves the original alone. Numbers and text never surprise you like this, because they cannot change; lists and dicts can.

Task 3 · the zip that lies

The total of the ledger is 3338.2. Someone wanted the positions "in order" and put sorted(shares) inside the zip. It runs, and prints a total that looks like money. First fill in an iteration table ON PAPER (ticker, shares, value, running total), then explain what went wrong and fix it.

total = 0.0
for t, n in zip(tickers, sorted(shares)):
    total += n * price[t]
print(total)

What total does the buggy loop print?

Show the answer

5910.2

total = 0.0
for t, n in zip(tickers, shares):
    total += n * price[t]
print(total)

The buggy version prints 5910.2. sorted(shares) is [2, 4, 10], and zip pairs by position, so AAPL gets 2 shares and VOO gets 10. Two lists that describe the same rows must stay in the same order. Rough check: VOO alone (5120.0) cannot be worth more than the whole ledger.

Task 6 · from text to a total

A ledger file arrives as lines of text. Loop over the lines, cut each one at the commas with .split(","), convert the pieces, and add up the value.

lines = ["AAPL,10,190.50", "NESN,4,102.30", "VOO,2,512.00"]

# your code here
Show the solution
lines = ["AAPL,10,190.50", "NESN,4,102.30", "VOO,2,512.00"]
total = 0.0
for line in lines:
    parts = line.split(",")
    total += int(parts[1]) * float(parts[2])
print("Task 6:", total)

It prints:

Task 6: 3338.2

split gives a list of three strings. They are text, so "10" * "190.50" would fail and "10" + "4" would join: convert with int() and float() first (session 2: data from files arrives as text).

Task 7 · the largest position, without max()

Find which position is worth the most, and print its ticker and value. Do not use max(): keep "the best so far" in two names and update them. Loop with zip(tickers, shares).

Show the solution
best_ticker, best_value = "", 0.0
for t, n in zip(tickers, shares):
    v = n * price[t]
    if v > best_value:
        best_ticker, best_value = t, v
print("Task 7:", best_ticker, f"{best_value:.2f}")

It prints:

Task 7: AAPL 1905.00

The pattern "best so far": start below any possible value, look at each item once, replace the best when something beats it. This is what max() does inside; now you can also keep WHICH item was best.

Session 4: functions, methods, modules, classes

The data these tasks start from
closes = [190.5, 187.2, 193.8, 185.1, 191.4, 198.6, 194.0]   # AAPL, day 0 to day 6

Task 1 · print is not return

Two functions that look almost the same. Predict EVERYTHING the program shows, line by line, in order. Then say what a and b hold.

def value_p(shares, price):
    print(shares * price)

def value_r(shares, price):
    return shares * price

a = value_p(4, 102.3)
b = value_r(4, 102.3)
print(a, b)

What does the last line print?

Show the answer

Task 1: None 409.2

value_p SHOWS 409.2 on the screen while it runs, then gives back nothing: every function without return returns None, so a is None. value_r shows nothing and hands 409.2 back to the program. A value on the screen is not a value in a variable (session 1's round, again).

Task 2 · two variables called total

Predict the print. Then explain: the function assigns to total. Why is the total outside still 100.0?

total = 100.0

def add_fee(amount):
    total = amount + 2.5
    return total

x = add_fee(40.0)
print(x, total)

What does the print show?

Show the answer

42.5 100.0

Assigning inside a function creates a LOCAL name. The total inside add_fee is a different variable that happens to share the name; it disappears when the call ends. The only way out of a function is return.

Task 3 · what the function changed

Two functions, each changes its parameter. Predict both prints. Why does the list outside change, and the number outside not?

def add_position(shares, n):
    shares.append(n)
    return len(shares)

def add_one(n):
    n = n + 1
    return n

shares = [10, 4, 2]
k = add_position(shares, 7)
print(k, shares)

m = 5
y = add_one(m)
print(m, y)

What does Task 3a print?

Show the answer

4 [10, 4, 2, 7]

Inside add_position, shares is a second name for the caller's list (session 3: two names, one list), and append changes that list in place. In add_one, n = n + 1 builds a NEW number and moves the local label n to it; the caller's 5 cannot change, because ints are immutable. Lists are mutable.

Task 6 · two functions for the ledger

The ledger is a list of (ticker, shares, price) tuples. Write position_value(shares, price) that returns the value of one position, and total_value(positions) that loops over the tuples, unpacks each one, and returns the sum of position_value for all of them. Both need a one-line docstring. Print total_value(ledger).

ledger = [("AAPL", 10, 190.5), ("NESN", 4, 102.3), ("VOO", 2, 512.0)]

# your code here
Show the solution
ledger = [("AAPL", 10, 190.5), ("NESN", 4, 102.3), ("VOO", 2, 512.0)]

def position_value(shares, price):
    """Value of one position, in CHF."""
    return shares * price

def total_value(positions):
    """Sum of the values of (ticker, shares, price) tuples."""
    total = 0.0
    for ticker, n, p in positions:
        total += position_value(n, p)
    return total

print("Task 6:", total_value(ledger))

It prints:

Task 6: 3338.2

One function per idea; the second one calls the first. The loop header unpacks each tuple into three names. return sits AFTER the loop, not inside it (Pavel's "Spot the lie").

Task 7 · a fee with defaults

Write fee(value, rate=0.001, minimum=5.0) that returns value × rate, but never less than minimum. Then print, on one line, fee(1000.0), fee(10000.0) and fee(10000.0, rate=0.002).

Show the solution
def fee(value, rate=0.001, minimum=5.0):
    """Broker fee: a share of the value, with a minimum charge."""
    return max(value * rate, minimum)

print("Task 7:", fee(1000.0), fee(10000.0), fee(10000.0, rate=0.002))

It prints:

Task 7: 5.0 10.0 20.0

Defaults make parameters optional. 1000 × 0.001 = 1.0 is below the minimum, so 5.0; 10000 × 0.001 = 10.0; the third call overrides rate by keyword and leaves minimum at its default. max() with two arguments picks the larger one.

Session 5: nested data, comprehensions, numpy, pandas

The data these tasks start from
import numpy as np
import pandas as pd

ledger = {
    "AAPL": {"shares": 10, "prices": [185.0, 188.2, 190.5]},
    "NESN": {"shares": 4, "prices": [104.1, 103.0, 102.3]},
    "VOO": {"shares": 2, "prices": [505.0, 509.9, 512.0]},
}
tickers = np.array(["AAPL", "NESN", "VOO"])
shares = np.array([10, 4, 2])
prices = np.array([[185.0, 188.2, 190.5],
                   [104.1, 103.0, 102.3],
                   [505.0, 509.9, 512.0]])
df = pd.DataFrame({"ticker": ["AAPL", "MSFT", "NESN", "VOO"],
                   "sector": ["tech", "tech", "food", "fund"],
                   "shares": [10, 3, 4, 2],
                   "price": [190.5, 410.0, 102.3, 512.0]})
df["value"] = df["shares"] * df["price"]

Task 1 · chains of look-ups

Read each chain from left to right. After every bracket, say what TYPE you have. Then predict the three printed values.

print(ledger["VOO"]["prices"][::-1][0])
print(len(ledger["AAPL"]))
print(ledger["NESN"]["shares"]
      * ledger["NESN"]["prices"][-1])

What is len(ledger["AAPL"])?

Show the answer

2

Line 1: dict → dict → list → reversed list → its first item, the last price. Line 2 is the trap: ledger["AAPL"] is the inner DICT, with two keys (shares, prices), so len is 2, not 3. Line 3: a number times a number.

Task 2 · say it in one sentence

For each comprehension: first say it in one English sentence ("the tickers whose…"), then predict what it prints. Check the brackets first: list, dict, or neither?

big = [t for t, d in ledger.items()
       if d["shares"] * d["prices"][-1] > 1000]
total = sum(d["shares"] for d in ledger.values())
counts = {t: len(d["prices"])
          for t, d in ledger.items()}
print(big)
print(total)
print(counts)

Which sentence describes the first comprehension?

Show the answer

The tickers whose position is worth more than 1000

1: "the tickers whose position is worth more than 1000", a list. 2: "the total number of shares", no brackets of its own, fed straight into sum. 3: "each ticker with how many prices it has", curly brackets with key: value, a dict.

Task 3 · count the scalars, get the shape

Pavel's rule: every single number inside the brackets removes a dimension; a : or a slice keeps it. Predict the four shapes without running anything.

print(prices[1].shape)
print(prices[:, [0, 2]].shape)
print(prices[:2, 1:].shape)
print(shares[:, None].shape)

What is prices[:, [0, 2]].shape?

Show the answer

(3, 2)

prices[1]: one number (row 1) → one dimension left, 3 long. [:, [0, 2]]: all rows, a LIST of two columns → (3, 2). [:2, 1:]: two rows, two columns. shares[:, None] keeps the 3 and adds a new direction of length 1: a column. When numpy surprises you, print .shape first.

Task 6 · a dict comprehension

In ONE dict comprehension over ledger.items(), build: each ticker → its change from the first to the last price, in percent, rounded to 2 decimals. Print it.

Show the solution
change = {t: round((d["prices"][-1] - d["prices"][0]) / d["prices"][0] * 100, 2)
          for t, d in ledger.items()}
print("Task 6:", change)

It prints:

Task 6: {'AAPL': 2.97, 'NESN': -1.73, 'VOO': 1.39}

Loop part first (for t, d in ledger.items()), then the key: value you keep. Write it as a loop first if the one-liner does not come; both are fine.

Task 7 · sort by yesterday's return

Sort the tickers of ledger by their LAST daily return (last price / the price before it − 1), largest first. Use sorted with key= and a lambda.

Show the solution
order = sorted(ledger, reverse=True,
               key=lambda t: ledger[t]["prices"][-1] / ledger[t]["prices"][-2] - 1)
print("Task 7:", order)

It prints:

Task 7: ['AAPL', 'VOO', 'NESN']

sorted(ledger) goes over the keys, the tickers. key= says what to compare for each ticker: here its last return (AAPL +1.22 %, VOO +0.41 %, NESN −0.68 %). reverse=True puts the largest first.

Task 8 · the portfolio on every day, no loop

With broadcasting: compute the value of every position on every day (a 3 × 3 array), then the portfolio total per day (one number per day), then the portfolio's daily return in percent, rounded to 2. No loops. Check one number by hand: AAPL on day 0 is 10 × 185 = 1850.

Show the solution
history = shares[:, None] * prices          # (3, 1) × (3, 3): shares stretched across the days
per_day = history.sum(axis=0)               # collapse the rows: one total per day
daily_return = (per_day[1:] / per_day[:-1] - 1) * 100
print("Task 8:", per_day, daily_return.round(2))

It prints:

Task 8: [3276.4 3313.8 3338.2] [1.14 0.74]

shares[:, None] makes shares a column, so it multiplies each ROW (position). axis=0 squeezes the rows away: one number per day. The two shifted slices per_day[1:] / per_day[:-1] give each day over the day before. Without [:, None], the shares would multiply the columns (days) instead, silently.