Hint: Add all transactions to initial balance [OK]
Common Mistakes:
Adding absolute values instead of signed values
Forgetting to add initial balance
Miscalculating sum of transactions
4. Identify the bug in this balance calculation code snippet:
balance = 50
transactions = [10, -20, 15]
for t in transactions:
balance = t
print(balance)
medium
A. The initial balance is not set
B. The transactions list is empty
C. The balance is overwritten instead of updated
D. The loop variable is incorrect
Solution
Step 1: Analyze the loop operation
Inside the loop, balance = t overwrites balance each time instead of adding.
Step 2: Understand correct update
It should be balance += t to add each transaction to balance.
Final Answer:
The balance is overwritten instead of updated -> Option C
Quick Check:
Use += to update balance, not = [OK]
Hint: Use += to add transactions, not = [OK]
Common Mistakes:
Using = instead of += inside loop
Assuming transactions list is empty
Ignoring initial balance
5. You need to design a balance calculation system that handles millions of transactions per day with real-time updates. Which design choice best supports scalability and accuracy?
hard
A. Ignore debits and only add credits to simplify calculation
B. Use a single database transaction to update balance after each transaction
C. Store all transactions in memory and recalculate balance on every request
D. Batch transactions and update balance periodically with distributed processing
Solution
Step 1: Consider scalability needs
Millions of transactions require efficient processing; single updates per transaction cause bottlenecks.
Step 2: Evaluate batch processing benefits
Batching with distributed processing reduces load and maintains accuracy by processing groups of transactions.
Step 3: Reject other options
Single DB transactions cause slowdowns, in-memory recalculation is memory-heavy and slow, ignoring debits causes incorrect balances.
Final Answer:
Batch transactions and update balance periodically with distributed processing -> Option D
Quick Check:
Batch + distributed processing = scalable & accurate [OK]
Hint: Batch and distribute processing for large-scale balance updates [OK]
Common Mistakes:
Updating balance per transaction causing bottlenecks
Recalculating balance on every request wasting memory