Data Science and Advanced Programming · Session 5

Session 5: the Wooclap questions

The reading questions from class, to redo at home.

Answer each question on paper first, without running anything. Then open the answer. If you got it wrong, run the code in your workspace and find the line where your prediction and Python part ways.

Reading tasks

Every task starts from this ledger:

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"])?

  1. 10
  2. KeyError
  3. 2
  4. 3
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?

  1. The tickers whose position is worth more than 1000
  2. The values of the positions above 1000
  3. The number of positions above 1000
  4. The tickers with more than 1000 shares
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?

  1. (2,)
  2. (2, 3)
  3. (3,)
  4. (3, 2)
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 4 · the scenario that changed the data

A colleague asks "what if NESN's last price were 0?" and tries it on a copy of the NESN row. Then they compute the REAL portfolio value, which should still be 3338.2. It prints something else. Find the line that is the problem, explain it, and fix it with one method call.

scenario = prices[1]
scenario[-1] = 0
real_values = shares * prices[:, -1]
print(real_values.sum())

Which line is the problem?

  1. scenario[-1] = 0
  2. print(real_values.sum())
  3. real_values = shares * prices[:, -1]
  4. scenario = prices[1]
Show the answer

scenario = prices[1]

The buggy version prints 2929.0: NESN's 409.2 vanished from the real data. A numpy slice is a VIEW of the same numbers, not a copy (lists slices are copies). scenario[-1] = 0 wrote into prices itself. .copy() makes an independent array.

Task 5 · labels or positions?

big keeps the rows worth more than 1000. The rows keep their labels. Predict all four values. Which of the last two lines uses labels, and which positions?

big = df[df["value"] > 1000]
print(big.index.tolist())
print(len(big))
print(big.loc[3, "ticker"])
print(big.iloc[1, 0])

What is big.iloc[1, 0]?

  1. MSFT
  2. NESN
  3. VOO
  4. AAPL
Show the answer

MSFT

NESN (409.2) is dropped, and labels 0, 1, 3 stay. .loc[3, "ticker"] finds the row LABELLED 3: VOO. .iloc[1, 0] counts POSITIONS: second row, first column: MSFT. big.loc[2, ...] would now fail, and so would big.iloc[3, ...].

Self-check (home questionnaire)

Check 1

What does this print?

ledger = {'A': {'p': [1, 2, 3]}}; print(ledger['A']['p'][-2:])
  1. 2
  2. [3]
  3. [2, 3]
  4. KeyError
Show the answer

[2, 3]

Check 2

What does this print?

print([x * 2 for x in [1, 2, 3] if x != 2])
  1. [4]
  2. [2, 4, 6]
  3. [1, 3]
  4. [2, 6]
Show the answer

[2, 6]

Check 3

What does this print?

print({k: len(k) for k in ["AAPL", "VOO"]})
  1. [4, 3]
  2. {'AAPL', 'VOO'}
  3. {4: 'AAPL', 3: 'VOO'}
  4. {'AAPL': 4, 'VOO': 3}
Show the answer

{'AAPL': 4, 'VOO': 3}

Check 4

What does this print?

print(sorted(["b", "a", "C"], key=lambda s: s.lower()))
  1. ['C', 'a', 'b']
  2. ['b', 'a', 'C']
  3. ['a', 'C', 'b']
  4. ['a', 'b', 'C']
Show the answer

['a', 'b', 'C']

Check 5

What does this print?

a = np.arange(6).reshape(2, 3); print(a.sum(axis=0))
  1. [ 3 12]
  2. [3 5 7]
  3. [0 1 2]
  4. 15
Show the answer

[3 5 7]

Check 6

What does this print?

a = np.arange(6).reshape(2, 3); print(a[:, 1:].shape)
  1. (2, 2)
  2. (2,)
  3. (1, 3)
  4. (2, 3)
Show the answer

(2, 2)

Check 7

What does this print?

print((np.array([1, 2, 3])[:, None] * np.array([10, 20])).shape)
  1. ValueError
  2. (3, 2)
  3. (3,)
  4. (2, 3)
Show the answer

(3, 2)

Check 8

What does this print?

a = np.zeros(3); b = a[:2]; b[0] = 5; print(a)
  1. [5. 5. 0.]
  2. [5. 0. 0.]
  3. [5. 0.]
  4. [0. 0. 0.]
Show the answer

[5. 0. 0.]

Check 9

What does this print?

df = pd.DataFrame({'v': [5, 1, 7]}); s = df[df['v'] > 2]; print(s.index.tolist(), s.iloc[1, 0])
  1. [0, 1] 1
  2. [0, 2] 1
  3. [0, 2] 7
  4. [0, 1] 7
Show the answer

[0, 2] 7

Check 10

Which error does this give?

df = pd.DataFrame({'v': [5, 1, 7]}); print(df[df['v'] > 2 and df['v'] < 6])
  1. It prints the row with 5
  2. ValueError
  3. TypeError
  4. KeyError
Show the answer

ValueError