Sets: Exercise Answers#
Investment Portfolio Diversification
1portfolio = {"WFC", "IBM", "APPL", "T", "CAT", "CVX"}
2interest = {"T", "F", "TSLA", "CVX", "CSCO", "KO"}
3
4# a. Stocks common to both lists
5common = portfolio & interest
6print("Common stocks:", common)
7
8# b. Stocks unique to each list
9only_portfolio = portfolio - interest
10only_interest = interest - portfolio
11print("Only in current portfolio:", only_portfolio)
12print("Only in interest list:", only_interest)
13
14# c. Suggested new portfolio (union of all unique stocks)
15new_portfolio = portfolio | interest
16print("Suggested new portfolio:", new_portfolio)
Common stocks: {'CVX', 'T'}
Only in current portfolio: {'WFC', 'CAT', 'IBM', 'APPL'}
Only in interest list: {'CSCO', 'KO', 'TSLA', 'F'}
Suggested new portfolio: {'WFC', 'CVX', 'IBM', 'CAT', 'T', 'TSLA', 'F', 'CSCO', 'KO', 'APPL'}
Expense Tracking
1# Sample data — in production this would be gathered via input()
2expenses = {
3 "rent_1": 1200.00,
4 "groceries_3": 85.50,
5 "utilities_5": 120.00,
6 "entertainment_7": 45.00,
7 "groceries_12": 92.30,
8 "entertainment_15": 30.00,
9 "utilities_20": 95.00,
10 "groceries_25": 110.20,
11 "entertainment_28": 60.00,
12}
13
14# a. Unique expense categories
15categories = set()
16for key in expenses:
17 category = key.rsplit('_', 1)[0]
18 categories.add(category)
19print("Unique categories:", categories)
20
21# b. Total amount per category
22totals = {}
23for key, amount in expenses.items():
24 category = key.rsplit('_', 1)[0]
25 totals[category] = totals.get(category, 0) + amount
26print("\nTotals by category:")
27for cat, total in sorted(totals.items()):
28 print(f" {cat}: ${total:.2f}")
29
30# c. Most frequently occurring expense category
31counts = {}
32for key in expenses:
33 category = key.rsplit('_', 1)[0]
34 counts[category] = counts.get(category, 0) + 1
35most_frequent = max(counts, key=counts.get)
36print(f"\nMost frequent category: {most_frequent} ({counts[most_frequent]} times)")
Unique categories: {'groceries', 'utilities', 'entertainment', 'rent'}
Totals by category:
entertainment: $135.00
groceries: $288.00
rent: $1200.00
utilities: $215.00
Most frequent category: groceries (3 times)
Input-based version (interactive):
1expenses = {}
2print("Enter expenses for the month. Press Enter with no category to finish.")
3day = 1
4while True:
5 category = input(f"Day {day} - Expense category (or Enter to stop): ").strip()
6 if not category:
7 break
8 try:
9 amount = float(input(f" Amount for {category}: "))
10 except ValueError:
11 print(" Invalid amount, skipping.")
12 continue
13 expenses[f"{category}_{day}"] = amount
14 day += 1
15
16# a. Unique categories
17categories = {key.rsplit('_', 1)[0] for key in expenses}
18print("\nUnique categories:", categories)
19
20# b. Totals per category
21totals = {}
22for key, amount in expenses.items():
23 cat = key.rsplit('_', 1)[0]
24 totals[cat] = totals.get(cat, 0) + amount
25for cat, total in sorted(totals.items()):
26 print(f" {cat}: ${total:.2f}")
27
28# c. Most frequent
29counts = {}
30for key in expenses:
31 cat = key.rsplit('_', 1)[0]
32 counts[cat] = counts.get(cat, 0) + 1
33if counts:
34 most_frequent = max(counts, key=counts.get)
35 print(f"Most frequent: {most_frequent} ({counts[most_frequent]} times)")
Enter expenses for the month. Press Enter with no category to finish.
---------------------------------------------------------------------------
StdinNotImplementedError Traceback (most recent call last)
Cell In[3], line 5
1 expenses = {}
2 print("Enter expenses for the month. Press Enter with no category to finish.")
3 day = 1
4 while True:
----> 5 category = input(f"Day {day} - Expense category (or Enter to stop): ").strip()
6 if not category:
7 break
8 try:
File ~/Documents/GitHub/jupyternotebooks/venv/lib/python3.14/site-packages/ipykernel/kernelbase.py:1402, in Kernel.raw_input(self, prompt)
1400 if not self._allow_stdin:
1401 msg = "raw_input was called, but this frontend does not support input requests."
-> 1402 raise StdinNotImplementedError(msg)
1403 return self._input_request(
1404 str(prompt),
1405 self._get_shell_context_var(self._shell_parent_ident),
1406 self.get_parent("shell"),
1407 password=False,
1408 )
StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
Bank Account Reconciliation
Note: The transaction IDs are used to build sets, since dictionaries are not hashable and cannot be placed directly in a set.
1customer = [
2 {'id': '1012', 'date': '20240502', 'memo': 'salary deposit', 'amount': 5051.25, 'category': 'income'},
3 {'id': '1013', 'date': '20240504', 'memo': 'supermarket', 'amount': 110.25, 'category': 'expense:food'},
4 {'id': '1014', 'date': '20240505', 'memo': 'headphones', 'amount': 71.95, 'category': 'expense:household'},
5 {'id': '1015', 'date': '20240506', 'memo': 'airfare', 'amount': 551.35, 'category': 'expense:travel'},
6 {'id': '1016', 'date': '20240508', 'memo': 'rental car', 'amount': 176.34, 'category': 'expense:travel'},
7]
8bank = [
9 {'id': '1012', 'date': '20240502', 'memo': 'salary deposit', 'amount': 5051.25, 'category': 'income'},
10 {'id': '1014', 'date': '20240505', 'memo': 'headphones', 'amount': 74.95, 'category': 'expense:household'},
11 {'id': '1015', 'date': '20240506', 'memo': 'airfare', 'amount': 551.35, 'category': 'expense:travel'},
12 {'id': '1016', 'date': '20240508', 'memo': 'rental car', 'amount': 176.34, 'category': 'expense:travel'},
13 {'id': '1017', 'date': '20240509', 'memo': 'Wikipedia donation', 'amount': 25.00, 'category': 'expense:charity'},
14]
15
16# Build lookup dicts and ID sets
17customer_dict = {}
18for t in customer:
19 customer_dict[t['id']] = t
20
21bank_dict = {}
22for t in bank:
23 bank_dict[t['id']] = t
24customer_ids = set(customer_dict.keys())
25bank_ids = set(bank_dict.keys())
26
27# a. Common transactions
28common_ids = customer_ids & bank_ids
29print("Common transaction IDs:", common_ids)
30
31# b. Unique to each
32only_customer = customer_ids - bank_ids
33only_bank = bank_ids - customer_ids
34print("Only in customer records:", only_customer)
35print("Only in bank records: ", only_bank)
36
37# c. Flag discrepancies (same ID, different amount or memo)
38print("\nDiscrepancies:")
39found = False
40for txn_id in common_ids:
41 c = customer_dict[txn_id]
42 b = bank_dict[txn_id]
43 if c['amount'] != b['amount'] or c['memo'] != b['memo']:
44 found = True
45 print(f" ID {txn_id}:")
46 print(f" Customer: amount=${c['amount']:.2f}, memo='{c['memo']}'")
47 print(f" Bank: amount=${b['amount']:.2f}, memo='{b['memo']}'")
48if not found:
49 print(" None")
50
51# Category totals across the full union of transactions
52# Use the bank record when both exist (bank is authoritative), otherwise the customer record
53print("\nCategory totals (union of all transactions):")
54category_totals = {}
55for txn_id in customer_ids | bank_ids:
56 txn = bank_dict.get(txn_id) or customer_dict.get(txn_id)
57 cat = txn['category']
58 category_totals[cat] = category_totals.get(cat, 0) + txn['amount']
59for cat, total in sorted(category_totals.items()):
60 print(f" {cat}: ${total:.2f}")
Common transaction IDs: {'1015', '1012', '1014', '1016'}
Only in customer records: {'1013'}
Only in bank records: {'1017'}
Discrepancies:
ID 1014:
Customer: amount=$71.95, memo='headphones'
Bank: amount=$74.95, memo='headphones'
Category totals (union of all transactions):
expense:charity: $25.00
expense:food: $110.25
expense:household: $74.95
expense:travel: $727.69
income: $5051.25