Practice/Stripe/Account Balance Manager
CodingMust
You are building an account balance management system for a payment platform. The system processes financial transactions across multiple accounts and needs to handle various business rules around balance validation and fund coverage.
The problem is divided into three progressive parts:
You will receive a list of transactions, where each transaction is a dictionary with an account_id string and an amount integer (positive for deposits, negative for withdrawals):
transactions = [ {"account_id": "account_A", "amount": 100}, {"account_id": "account_B", "amount": 50}, {"account_id": "account_A", "amount": -30}, {"account_id": "account_B", "amount": -80}, ]
Implement a function get_account_balances(transactions) that processes all transactions and returns the final balance for each account that has a positive balance.
` transactions = [ {"account_id": "account_A", "amount": 100}, {"account_id": "account_B", "amount": 50}, {"account_id": "account_A", "amount": -30}, {"account_id": "account_C", "amount": 200}, {"account_id": "account_B", "amount": -50}, ]
get_account_balances(transactions)
`
Extend your solution to validate each transaction before processing. A transaction should be rejected if it would cause the account balance to become negative. Return both the final balances and the list of rejected transactions.
Implement process_transactions(transactions) that returns a tuple of (balances, rejected_transactions).
` transactions = [ {"account_id": "account_A", "amount": 100}, {"account_id": "account_A", "amount": -150}, # Would make balance -50 {"account_id": "account_B", "amount": 50}, {"account_id": "account_A", "amount": -80}, # Valid: 100 - 80 = 20 {"account_id": "account_B", "amount": -100}, # Would make balance -50 ]
process_transactions(transactions)
`
The platform can now provide financial assistance. When a transaction would cause a negative balance, instead of rejecting it, the system should transfer funds from a designated platform account to cover the shortfall.
Implement process_with_coverage(transactions, platform_account_id) that returns the total amount of funds transferred from the platform account to cover all shortfalls.
` transactions = [ {"account_id": "platform", "amount": 1000}, {"account_id": "account_A", "amount": 100}, {"account_id": "account_A", "amount": -150}, # Needs 50 coverage {"account_id": "account_B", "amount": 50}, {"account_id": "account_B", "amount": -100}, # Needs 50 coverage {"account_id": "account_A", "amount": -30}, # Needs 30 coverage ]
process_with_coverage(transactions, "platform")
`