Skip to content

Commit 8518ca1

Browse files
feat(accounts-transactions): add accounts transactions challenge
1 parent c8f70ae commit 8518ca1

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
from bisect import bisect_right
2+
3+
4+
class Account():
5+
def __init__(self, account_id, ts, value):
6+
self.account_id = account_id
7+
self.timestamps = [ts]
8+
self.balances = [value]
9+
self.values = [value]
10+
11+
12+
class Accounts:
13+
def __init__(self):
14+
self.accounts = {}
15+
16+
def credit(self, account_id, ts, value):
17+
if account_id not in self.accounts:
18+
self.accounts.setdefault(
19+
account_id, Account(account_id, ts, value))
20+
else:
21+
account = self.accounts[account_id]
22+
account.timestamps.append(ts)
23+
account.balances.append(account.balances[-1] + value)
24+
account.values.append(value)
25+
26+
def debit(self, account_id, ts, value):
27+
if account_id not in self.accounts:
28+
self.accounts.setdefault(
29+
account_id, Account(account_id, ts, -value))
30+
else:
31+
account = self.accounts[account_id]
32+
account.timestamps.append(ts)
33+
account.balances.append(account.balances[-1] - value)
34+
account.values.append(-value)
35+
36+
def current(self, account_id):
37+
if account_id not in self.accounts:
38+
return None
39+
account = self.accounts[account_id]
40+
return account.balances[-1]
41+
42+
def balance_change(self, account_id, start_ts, end_ts):
43+
if account_id not in self.accounts:
44+
return None
45+
account = self.accounts[account_id]
46+
start_idx = bisect_right(account.timestamps, start_ts)
47+
end_idx = bisect_right(account.timestamps, end_ts)
48+
49+
return account.balances[end_idx - 1] - account.balances[start_idx - 1]
50+
51+
52+
accounts = Accounts()
53+
accounts.credit(1, 1, 100)
54+
accounts.debit(1, 3, 50)
55+
accounts.credit(1, 5, 20)
56+
accounts.debit(1, 7, 10)
57+
print(accounts.current(1))
58+
print(accounts.balance_change(1, 2, 6))
59+
print(accounts.balance_change(1, 3, 5))

0 commit comments

Comments
 (0)