Data Science and Advanced Programming · Session 6

Session 6: solutions

The writing tasks from week-06/workshop/, solved.

Try each task in your workspace first. Open a solution only when your code runs, or when you have been stuck for a while. Your solution can be different and still right: compare what it prints. The reading tasks and their answers are on the Questions page.

Writing tasks

Task 6 · load the ledger by hand

Read ledger.csv with open(): skip the header, split each line, convert shares with int() and price with float(). Keep the good rows as (ticker, shares, price) tuples in a list; skip a bad row with try / except ValueError, printing which ticker you skipped. Then print the number of good rows and the total value, rounded to 2.

Show the solution
positions = []
with open(ledger_path, encoding="utf-8") as f:
    f.readline()
    for line in f:
        ticker, name, shares, price = line.strip().split(",")
        try:
            positions.append((ticker, int(shares), float(price)))
        except ValueError:
            print("skipped", ticker)
total = 0.0
for ticker, shares, price in positions:
    total += shares * price
print("Task 6:", len(positions), round(total, 2))

It prints:

skipped MSFT
Task 6: 3 3338.2

This is the load half of Pavel's report.py. Keep the try around the two conversions only: that is where a ValueError can come from. 3338.2 is the ledger total we have used since session 2.

Task 7 · write a report, read it back

Write report.txt in HERE: one line per good position, "AAPL 1905.00" (ticker, a space, the value with 2 decimals), then a last line "total 3338.20". Use open(..., "w") and f.write(...); do not forget the "\n". Then read the file back and print it.

Show the solution
positions = [("AAPL", 10, 190.5), ("NESN", 4, 102.3), ("VOO", 2, 512.0)]
report = HERE / "report.txt"
total = 0.0
with open(report, "w", encoding="utf-8") as out:
    for ticker, shares, price in positions:
        out.write(f"{ticker} {shares * price:.2f}\n")
        total += shares * price
    out.write(f"total {total:.2f}\n")
print(report.read_text(encoding="utf-8"))

It prints:

AAPL 1905.00
NESN 409.20
VOO 1024.00
total 3338.20

write() does not add a line break, unlike print. Without "\n" the whole report is one long line. :.2f always shows two decimals, which is what a report needs: 1024.00, not 1024.0.

Task 8 · the Swiss export

ledger_eu.csv is the same ledger as Excel exports it in Switzerland: ; between fields and , as the decimal mark. First read it with plain pd.read_csv and print the columns you get. Then give read_csv the two options that fix it, and print the total value.

Show the solution
wrong = pd.read_csv(HERE / "ledger_eu.csv")
print("Task 8:", list(wrong.columns))
eu = pd.read_csv(HERE / "ledger_eu.csv", sep=";", decimal=",")
print("Task 8:", round((eu["shares"] * eu["price"]).sum(), 2))

It prints:

Task 8: ['ticker;shares;price']
Task 8: 3338.2

Without sep=";" pandas looks for commas, finds none in the header, and makes ONE column called 'ticker;shares;price'. No error: a silent lie. sep=";" splits the fields, decimal="," reads 190,50 as 190.5. Always print df.columns (or df.head()) after read_csv.

Task 9 · raise with a clear message

Write a function to_shares(text) that returns int(text), but raises ValueError("missing shares") when text is the empty string. Then call it on "10" and on "" inside a try, and print the result or the error message.

Show the solution
def to_shares(text):
    if text == "":
        raise ValueError("missing shares")
    return int(text)

for text in ["10", ""]:
    try:
        print("Task 9:", to_shares(text))
    except ValueError as e:
        print("Task 9: error:", e)

It prints:

Task 9: 10
Task 9: error: missing shares

int("") would raise ValueError anyway, but with a message nobody understands: invalid literal for int() with base 10: ''. raise lets YOU decide the message. except ValueError as e gives you the error object; printing it prints the message.

Task 10 · today's prices from a second file

prices_today.csv has the new price of each ticker, in a different order. Read it into a dict ticker → price (with open() or with pandas), then compute the value of the three good positions at TODAY's prices. Print the total, rounded to 2.

Show the solution
positions = [("AAPL", 10, 190.5), ("NESN", 4, 102.3), ("VOO", 2, 512.0)]
today = {}
with open(HERE / "prices_today.csv", encoding="utf-8") as f:
    f.readline()
    for line in f:
        ticker, price = line.strip().split(",")
        today[ticker] = float(price)
total = 0.0
for ticker, shares, old_price in positions:
    total += shares * today[ticker]
print("Task 10:", round(total, 2))

It prints:

Task 10: 3322.8

The dict is what makes the different order harmless: you look each ticker up by name, not by position. With pandas: dict(zip(df["ticker"], df["price"])) gives the same dict.

★ Harder: classic puzzles

★ Task 11 · Lines, characters, bytes (the Unix wc classic)

Read ledger.csv as one string. Print three numbers: how many lines, how many characters, and how many BYTES the file takes on disk (len of the text encoded in UTF-8, or the file size from pathlib). Characters and bytes differ by exactly one. Which letter is responsible?

Show the solution
text = ledger_path.read_text(encoding="utf-8")
print("Task 11:", len(text.splitlines()), len(text), len(text.encode("utf-8")), ledger_path.stat().st_size)

It prints:

Task 11: 5 112 113 113

The é of Nestlé is one character but two bytes in UTF-8. That is what encoding="utf-8" is about: open the file with the wrong encoding and é turns into é.

★ Task 12 · An error log with line numbers

Go through ledger.csv and write errors.txt with one line per bad row: its LINE NUMBER in the file (the header is line 1), the ticker and the error message. Use enumerate(f, start=1). Print the file afterwards.

Show the solution
with open(ledger_path, encoding="utf-8") as f, open(HERE / "errors.txt", "w", encoding="utf-8") as log:
    for number, line in enumerate(f, start=1):
        if number == 1:
            continue
        ticker, name, shares, price = line.strip().split(",")
        try:
            int(shares), float(price)
        except ValueError as e:
            log.write(f"line {number}: {ticker}: {e}\n")
print((HERE / "errors.txt").read_text(encoding="utf-8"))

It prints:

line 5: MSFT: invalid literal for int() with base 10: ''

A data pipeline should not just skip bad rows silently: it should say WHICH rows, so a human can fix the source. Line numbers are what makes the log useful: open ledger.csv, go to line 5, see the empty field.

★ Task 13 · The last n lines (the Unix tail classic)

Write tail(path, n) that returns the last n lines of a file as a list of strings without their "\n". It must work for n larger than the file, and for n = 0 (watch out: lines[-0:] is the WHOLE list). Print tail(ledger_path, 2), tail(ledger_path, 0) and len(tail(ledger_path, 99)).

Show the solution
def tail(path, n):
    lines = Path(path).read_text(encoding="utf-8").splitlines()
    if n <= 0:
        return []
    return lines[-n:]

print("Task 13:", tail(ledger_path, 2))
print("Task 13:", tail(ledger_path, 0), len(tail(ledger_path, 99)))

It prints:

Task 13: ['VOO,Vanguard,2,512.00', 'MSFT,Microsoft,,410.00']
Task 13: [] 5

Slicing never fails on a too-large n: lines[-99:] just gives every line. But -0 is 0, and lines[0:] is everything: the edge case that needs its own if. splitlines() removes the "\n" for you.

Extra practice

Practice 1 · Reverse a file (the Unix tac classic)

Write reversed.csv: the header first, then the data rows of ledger.csv in reverse order (MSFT first). Print the file.

Show the solution
lines = ledger_path.read_text(encoding="utf-8").splitlines()
out = [lines[0]] + lines[1:][::-1]
(HERE / "reversed.csv").write_text("\n".join(out) + "\n", encoding="utf-8")
print((HERE / "reversed.csv").read_text(encoding="utf-8"))

It prints:

ticker,name,shares,price
MSFT,Microsoft,,410.00
AAPL,Apple,10,190.50

lines[1:] drops the header, [::-1] reverses what is left (session 3 slicing). "\n".join puts the line breaks back between the lines; the + "\n" ends the last one.

Practice 2 · Fill the gap instead of dropping it

With pandas: read ledger.csv, replace MSFT's missing shares by 0 (fillna), convert shares back to int, add a value column, and write report.csv without the index. Read report.csv back and print its shape and the value column as a list.

Show the solution
df = pd.read_csv(ledger_path)
df["shares"] = df["shares"].fillna(0).astype(int)
df["value"] = df["shares"] * df["price"]
df.to_csv(HERE / "report.csv", index=False)
back = pd.read_csv(HERE / "report.csv")
print(back.shape, back["value"].tolist())

It prints:

(4, 5) [1905.0, 409.2, 1024.0, 0.0]

dropna removes the row; fillna keeps it with a value you choose. Which one is right depends on the question: for "total value" 0 shares is honest; for "average price per share" it is not. index=False stops pandas from writing its row labels as an extra unnamed column.

Practice 3 · Count by first letter, into a file

For the tickers of ledger.csv, count how many start with each letter, in a dict. Write the counts to counts.txt, one "letter count" per line, in alphabetical order. Print the file.

Show the solution
counts = {}
with open(ledger_path, encoding="utf-8") as f:
    f.readline()
    for line in f:
        letter = line[0]
        counts[letter] = counts.get(letter, 0) + 1
with open(HERE / "counts.txt", "w", encoding="utf-8") as out:
    for letter in sorted(counts):
        out.write(f"{letter} {counts[letter]}\n")
print((HERE / "counts.txt").read_text(encoding="utf-8"))

It prints:

A 1
M 1
N 1
V 1

counts.get(letter, 0) + 1 is the counting idiom from session 5: start at 0 the first time a key appears. sorted(counts) goes over the keys in alphabetical order.