Fundamental Concept Review:#

Case Study Problems#

Here are the practice question answers directly.

Practice Question Answers#

Modify filter_by_symbol so it can filter by both account and symbol#

1def filter_by_account_and_symbol(transactions, account, symbol):
2    """Return transactions matching both an account and a stock symbol."""
3    matches = []
4
5    for transaction in transactions:
6        if transaction.account == account and transaction.symbol == symbol:
7            matches.append(transaction)
8
9    return matches
1Example:
  Cell In[2], line 1
    Example:
            ^
SyntaxError: invalid syntax

filter_by_account_and_symbol(transactions, “A100”, “AAPL”)

This uses filtering, selection, and list accumulation.

Write transactions_for_account(transactions, account)#

1def transactions_for_account(transactions, account):
2    """Return all transactions for a specific account."""
3    matches = []
4
5    for transaction in transactions:
6        if transaction.account == account:
7            matches.append(transaction)
8
9    return matches

Example:

transactions_for_account(transactions, “A100”)

This is also a filtering pattern. We keep only the transactions whose account matches the requested account.#

Write total_commissions(transactions)#

def total_commissions(transactions):
    """Return the total commissions paid across all transactions."""
    total = 0

    for transaction in transactions:
        total += transaction.commission

    return total

Example:

total_commissions(transactions)

This uses accumulation. We start with 0 and add each transaction’s commission.


Write symbols_by_account(transactions)#

def symbols_by_account(transactions):
    """
    Return a dictionary where each key is an account and each value
    is a set of stock symbols traded by that account.
    """
    account_symbols = {}

    for transaction in transactions:
        account = transaction.account
        symbol = transaction.symbol

        if account not in account_symbols:
            account_symbols[account] = set()

        account_symbols[account].add(symbol)

    return account_symbols

Example:

symbols_by_account(transactions)

Possible result:

{
    "A100": {"AAPL", "MSFT"},
    "A200": {"NVDA", "TSLA"},
    "A300": {"AAPL", "NVDA"}
}

This combines grouping, searching dictionary keys, set accumulation, and state tracking.


Write largest_transaction_by_symbol(transactions)#

def largest_transaction_by_symbol(transactions):
    """
    Return a dictionary mapping each symbol to the transaction
    with the largest gross value for that symbol.
    """
    largest_by_symbol = {}

    for transaction in transactions:
        symbol = transaction.symbol

        if symbol not in largest_by_symbol:
            largest_by_symbol[symbol] = transaction
        elif transaction.gross_value() > largest_by_symbol[symbol].gross_value():
            largest_by_symbol[symbol] = transaction

    return largest_by_symbol

Example:

largest_transaction_by_symbol(transactions)

This combines grouping and maximum tracking. For each symbol, the dictionary remembers the largest transaction seen so far.


Write has_short_position(transactions)#

This version reuses the earlier net_positions_by_symbol function.

def has_short_position(transactions):
    """Return True if any symbol has a negative net position."""
    positions = net_positions_by_symbol(transactions)

    for symbol in positions:
        if positions[symbol] < 0:
            return True

    return False

Example:

has_short_position(transactions)

This uses decomposition because it relies on net_positions_by_symbol instead of repeating that logic.

It also uses searching because it looks for any symbol with a negative position.


Write validate_no_duplicate_transaction_ids(transactions)#

def validate_no_duplicate_transaction_ids(transactions):
    """
    Return True if there are no duplicate transaction IDs.
    Return False if any transaction ID appears more than once.
    """
    seen_ids = set()

    for transaction in transactions:
        if transaction.transaction_id in seen_ids:
            return False

        seen_ids.add(transaction.transaction_id)

    return True

Example:

validate_no_duplicate_transaction_ids(transactions)

This uses searching, state tracking, and set accumulation.

The set seen_ids remembers which transaction IDs have already appeared.

A more diagnostic version could return the duplicate IDs:

def find_duplicate_transaction_ids(transactions):
    """Return a set of transaction IDs that appear more than once."""
    seen_ids = set()
    duplicate_ids = set()

    for transaction in transactions:
        if transaction.transaction_id in seen_ids:
            duplicate_ids.add(transaction.transaction_id)
        else:
            seen_ids.add(transaction.transaction_id)

    return duplicate_ids

Example:

find_duplicate_transaction_ids(transactions)

Explain which algorithmic patterns appear in each function#

Function

Main patterns

filter_by_account_and_symbol

Filtering, selection, list accumulation

transactions_for_account

Filtering, selection, list accumulation

total_commissions

Accumulation

symbols_by_account

Grouping, searching dictionary keys, set accumulation, state tracking

largest_transaction_by_symbol

Grouping, maximum tracking, state tracking

has_short_position

Decomposition, searching, selection

validate_no_duplicate_transaction_ids

Searching, state tracking, set accumulation, early return

find_duplicate_transaction_ids

Searching, state tracking, set accumulation, filtering duplicates

The important idea is that these are not unrelated problems. They are combinations of the same core patterns.

For example, this function:

def symbols_by_account(transactions):
    account_symbols = {}

    for transaction in transactions:
        account = transaction.account
        symbol = transaction.symbol

        if account not in account_symbols:
            account_symbols[account] = set()

        account_symbols[account].add(symbol)

    return account_symbols

combines:

  • grouping: each account becomes a dictionary key

  • searching: we check whether the account is already in the dictionary

  • accumulation: we add symbols to a set

  • state tracking: the dictionary remembers what has been seen so far

Exercise Answers#

  1. Loan Amortization Schedule — sequence, selection, and repetition to calculate monthly payments.

 1def loan_amortization(principal, annual_rate, years):
 2    """
 3    Generate a monthly loan amortization schedule.
 4
 5    Returns a list of dicts with keys: month, payment, principal, interest, balance.
 6    """
 7    monthly_rate = annual_rate / 12
 8    n_payments   = years * 12
 9
10    if monthly_rate == 0:
11        monthly_payment = principal / n_payments
12    else:
13        monthly_payment = (principal * monthly_rate *
14                           (1 + monthly_rate) ** n_payments /
15                           ((1 + monthly_rate) ** n_payments - 1))
16
17    balance  = principal
18    schedule = []
19    for month in range(1, n_payments + 1):
20        interest          = balance * monthly_rate
21        principal_payment = monthly_payment - interest
22        balance          -= principal_payment
23        schedule.append({
24            'month':     month,
25            'payment':   round(monthly_payment, 2),
26            'principal': round(principal_payment, 2),
27            'interest':  round(interest, 2),
28            'balance':   round(max(balance, 0), 2),
29        })
30    return schedule
31
32# Example: $200,000 mortgage at 6% for 30 years
33schedule = loan_amortization(200_000, 0.06, 30)
34print(f"Monthly payment: ${schedule[0]['payment']:,.2f}")
35print(f"{'Month':>6} {'Payment':>10} {'Principal':>10} {'Interest':>10} {'Balance':>12}")
36for row in schedule[:6]:
37    print(f"{row['month']:>6} {row['payment']:>10,.2f} {row['principal']:>10,.2f} "
38          f"{row['interest']:>10,.2f} {row['balance']:>12,.2f}")
39print('...')
40print(f"Total payments: ${sum(r['payment'] for r in schedule):,.2f}")
41print(f"Total interest: ${sum(r['interest'] for r in schedule):,.2f}")
Monthly payment: $1,199.10
 Month    Payment  Principal   Interest      Balance
     1   1,199.10     199.10   1,000.00   199,800.90
     2   1,199.10     200.10     999.00   199,600.80
     3   1,199.10     201.10     998.00   199,399.71
     4   1,199.10     202.10     997.00   199,197.60
     5   1,199.10     203.11     995.99   198,994.49
     6   1,199.10     204.13     994.97   198,790.36
...
Total payments: $431,676.00
Total interest: $231,676.43
  1. Stock Portfolio Class — groups related data and analysis functions for a collection of investments.

 1class StockPortfolio:
 2    """Tracks stock holdings and computes portfolio metrics."""
 3
 4    def __init__(self):
 5        self._holdings = {}   # symbol -> {'shares': float, 'cost_basis': float}
 6
 7    def buy(self, symbol, shares, price):
 8        if symbol in self._holdings:
 9            h = self._holdings[symbol]
10            total_shares = h['shares'] + shares
11            total_cost   = h['cost_basis'] * h['shares'] + price * shares
12            self._holdings[symbol] = {'shares': total_shares,
13                                      'cost_basis': total_cost / total_shares}
14        else:
15            self._holdings[symbol] = {'shares': shares, 'cost_basis': price}
16
17    def sell(self, symbol, shares):
18        if symbol not in self._holdings or self._holdings[symbol]['shares'] < shares:
19            raise ValueError(f'Insufficient shares of {symbol}')
20        self._holdings[symbol]['shares'] -= shares
21        if self._holdings[symbol]['shares'] == 0:
22            del self._holdings[symbol]
23
24    def market_value(self, prices):
25        return sum(h['shares'] * prices.get(sym, 0)
26                   for sym, h in self._holdings.items())
27
28    def gain_loss(self, prices):
29        cost = sum(h['shares'] * h['cost_basis'] for h in self._holdings.values())
30        return self.market_value(prices) - cost
31
32    def summary(self, prices):
33        header = f"{'Symbol':8} {'Shares':>8} {'Cost':>10} {'Price':>10} {'Value':>12} {'Gain/Loss':>12}"
34        print(header)
35        print('-' * len(header))
36        for sym, h in sorted(self._holdings.items()):
37            price = prices.get(sym, 0)
38            value = h['shares'] * price
39            gl    = value - h['shares'] * h['cost_basis']
40            print(f"{sym:8} {h['shares']:>8.0f} {h['cost_basis']:>10.2f} "
41                  f"{price:>10.2f} {value:>12.2f} {gl:>12.2f}")
42        print(f"\nTotal market value : ${self.market_value(prices):,.2f}")
43        print(f"Total gain / loss  : ${self.gain_loss(prices):,.2f}")
44
45
46portfolio = StockPortfolio()
47portfolio.buy('AAPL', 50, 150.00)
48portfolio.buy('MSFT', 30, 280.00)
49portfolio.buy('AAPL', 20, 160.00)   # average-down purchase
50
51current_prices = {'AAPL': 175.00, 'MSFT': 310.00}
52portfolio.summary(current_prices)
Symbol     Shares       Cost      Price        Value    Gain/Loss
-----------------------------------------------------------------
AAPL           70     152.86     175.00     12250.00      1550.00
MSFT           30     280.00     310.00      9300.00       900.00

Total market value : $21,550.00
Total gain / loss  : $2,450.00
  1. Transaction Validation — validate dates, amounts, and categories for a list of financial transactions.

 1import datetime
 2
 3VALID_CATEGORIES = {'income', 'expense', 'transfer'}
 4
 5def validate_transactions(transactions):
 6    """
 7    Validate a list of transaction dicts.
 8
 9    Each transaction must have:
10      - 'date'     : ISO-format string (YYYY-MM-DD)
11      - 'amount'   : positive number
12      - 'category' : one of 'income', 'expense', 'transfer'
13
14    Returns a list of error strings (empty if all valid).
15    """
16    errors = []
17    for i, txn in enumerate(transactions):
18        prefix = f'Transaction {i}'
19
20        # date
21        if 'date' not in txn:
22            errors.append(f'{prefix}: missing date')
23        else:
24            try:
25                datetime.date.fromisoformat(str(txn['date']))
26            except (ValueError, TypeError):
27                errors.append(f"{prefix}: invalid date '{txn['date']}'")
28
29        # amount
30        if 'amount' not in txn:
31            errors.append(f'{prefix}: missing amount')
32        elif not isinstance(txn['amount'], (int, float)) or txn['amount'] <= 0:
33            errors.append(f"{prefix}: amount must be a positive number")
34
35        # category
36        if 'category' not in txn:
37            errors.append(f'{prefix}: missing category')
38        elif txn['category'] not in VALID_CATEGORIES:
39            errors.append(f"{prefix}: invalid category '{txn['category']}'")
40
41    return errors
42
43
44transactions = [
45    {'date': '2024-01-15', 'amount': 2500.00, 'category': 'income'},
46    {'date': '2024-13-01', 'amount':  150.00, 'category': 'expense'},   # bad date
47    {'date': '2024-01-20', 'amount':   -50.0, 'category': 'expense'},   # negative amount
48    {'date': '2024-01-21', 'amount':   75.00, 'category': 'luxury'},    # bad category
49    {'date': '2024-01-22', 'amount':  200.00, 'category': 'transfer'},
50]
51
52errors = validate_transactions(transactions)
53if errors:
54    print('Validation errors:')
55    for e in errors:
56        print(f'  {e}')
57else:
58    print('All transactions valid.')
Validation errors:
  Transaction 1: invalid date '2024-13-01'
  Transaction 2: amount must be a positive number
  Transaction 3: invalid category 'luxury'
  1. Compound Interest Simulation — compare growth across various rates and time periods.

 1def compound_interest(principal, annual_rate, years, compounds_per_year=12):
 2    """Return final amount and total interest after compounding."""
 3    amount   = principal * (1 + annual_rate / compounds_per_year) ** (compounds_per_year * years)
 4    interest = amount - principal
 5    return round(amount, 2), round(interest, 2)
 6
 7principal = 10_000
 8rates     = [0.03, 0.05, 0.07, 0.10]
 9periods   = [5, 10, 20, 30]
10
11print(f"{'Rate':>6}  {'Years':>6}  {'Final Value':>14}  {'Total Interest':>16}")
12print('-' * 50)
13for rate in rates:
14    for years in periods:
15        amount, interest = compound_interest(principal, rate, years)
16        print(f"{rate:>6.0%}  {years:>6}  {amount:>14,.2f}  {interest:>16,.2f}")
17    print()
  Rate   Years     Final Value    Total Interest
--------------------------------------------------
    3%       5       11,616.17          1,616.17
    3%      10       13,493.54          3,493.54
    3%      20       18,207.55          8,207.55
    3%      30       24,568.42         14,568.42

    5%       5       12,833.59          2,833.59
    5%      10       16,470.09          6,470.09
    5%      20       27,126.40         17,126.40
    5%      30       44,677.44         34,677.44

    7%       5       14,176.25          4,176.25
    7%      10       20,096.61         10,096.61
    7%      20       40,387.39         30,387.39
    7%      30       81,164.97         71,164.97

   10%       5       16,453.09          6,453.09
   10%      10       27,070.41         17,070.41
   10%      20       73,280.74         63,280.74
   10%      30      198,373.99        188,373.99
  1. Personal Finance Package Structure — a package with modules for budgeting, investing, and debt management.

Create the following directory structure:

personal_finance/
├── __init__.py
├── budgeting.py
├── investing.py
└── debt.py

personal_finance/__init__.py

"""personal_finance — modules for budgeting, investing, and debt management."""
from .budgeting import Budget
from .investing import Portfolio
from .debt      import Loan

personal_finance/budgeting.py

"""budgeting — track income and expenses by category."""

class Budget:
    def __init__(self):
        self._items = []

    def add_item(self, description, amount, category):
        self._items.append({'description': description,
                            'amount': amount, 'category': category})

    def total_by_category(self):
        categories = {item['category'] for item in self._items}
        return {cat: sum(i['amount'] for i in self._items if i['category'] == cat)
                for cat in categories}

    def net(self):
        totals = self.total_by_category()
        return totals.get('income', 0) - totals.get('expense', 0)

personal_finance/investing.py

"""investing — simple stock portfolio tracker."""

class Portfolio:
    def __init__(self):
        self._holdings = {}

    def buy(self, symbol, shares, price):
        prev = self._holdings.get(symbol, {'shares': 0, 'cost_basis': 0})
        total_shares = prev['shares'] + shares
        total_cost   = prev['cost_basis'] * prev['shares'] + price * shares
        self._holdings[symbol] = {'shares': total_shares,
                                  'cost_basis': total_cost / total_shares}

    def market_value(self, prices):
        return sum(h['shares'] * prices.get(s, 0) for s, h in self._holdings.items())

personal_finance/debt.py

"""debt — loan payment calculations."""

class Loan:
    def __init__(self, principal, annual_rate, years):
        self.principal    = principal
        self.annual_rate  = annual_rate
        self.years        = years

    def monthly_payment(self):
        r = self.annual_rate / 12
        n = self.years * 12
        if r == 0:
            return self.principal / n
        return self.principal * r * (1 + r)**n / ((1 + r)**n - 1)

    def total_interest(self):
        return self.monthly_payment() * self.years * 12 - self.principal

Usage:

from personal_finance import Budget, Portfolio, Loan

b = Budget()
b.add_item('Salary',    5000, 'income')
b.add_item('Rent',      1500, 'expense')
b.add_item('Groceries',  400, 'expense')
print(b.total_by_category())  # {'income': 5000, 'expense': 1900}
print(f'Net: ${b.net():,.2f}')  # Net: $3,100.00