We accidentally dropped the database where we store the current billing status for our advertisers. Fortunately, we still have the logs for all the transactions they did, and we can use this to recreate the dropped data.
You are asked to process the financial transactions from the old system to build up a BillingStatus per user to be stored in our new system.
You should create a class called BillingStatus, which will represent an account state. Each financial transaction represents a modification to a BillingStatus. A BillingStatus should be able to ingest new transactions that are generated in our own systems.
Given a collection of financial transactions, we want to generate a BillingStatus instance for each user. This can be represented as a dict:
{user_id: BillingStatus(), user_id2: BillingStatus()}
Our BillingStatus class should start with two monetary columns:
'ad_delivery_pennies': 0, 'payment_pennies': 0
Each transaction can have multiple monetary columns. Upon processing a transaction, the values in the monetary columns should be added to the current value in the BillingStatus.
Given this input:
monetary_columns = ('ad_delivery_pennies', 'payment_pennies')
transactions = {'ff8bc1c2-8d45-11e9-bc42-526af7764f64': {'user_id': 1, 'ad_delivery_pennies': 1000, 'transaction_timestamp': 1500000001},
'ff8bc2e4-8d45-11e9-bc42-526af7764f64': {'user_id': 1, 'ad_delivery_pennies': 1000, 'transaction_timestamp': 1500000002},
'ff8bc4ec-8d45-11e9-bc42-526af7764f64': {'user_id': 1, 'payment_pennies': 500, 'transaction_timestamp': 1500000003},
'fv24z4ec-8d45-11e9-bc42-526af7764f64': {'user_id': 1, 'ad_delivery_pennies': 1000, 'payment_pennies': 500, 'transaction_timestamp': 1500000004}
}
Expected Output (format however you want):
{1: BillingStatus({'ad_delivery_pennies': 3000, 'payment_pennies': 1000})}
# INSERT YOUR CODE BELOW THIS LINE
这道题考察的是按用户聚合交易并维护账户状态的设计:需要实现一个 BillingStatus,用来累加每个用户在各个 monetary column 上的金额。做题时通常先为每个 user_id 创建一个状态对象,再遍历 transactions;对于每笔交易,只把出现在 monetary_columns 中的字段加到对应用户的累计值里,像 transaction_timestamp 这类非金额字段应忽略。数据结构上可以用字典保存 user_id 到 BillingStatus 的映射,BillingStatus 内部再用字典保存各金额字段的当前总和。题目本质上是哈希表 + 增量聚合,重点在于正确初始化字段、处理多列金额以及保持对未知字段的过滤。