Simple Bank System
__init__(self, balance: List[int])
: Initializes the object with the balance.transfer(self, account1: int, account2: int, money: int) -> bool
: Transfers money from account1 to account2. Returns true if successful.deposit(self, account: int, money: int) -> bool
: Deposits money into an account. Returns true if successful.withdraw(self, account: int, money: int) -> bool
: Withdraws money from an account. Returns true if successful.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| class Bank:
def __init__(self, balance: List[int]):
self.balance = balance
def transfer(self, account1: int, account2: int, money: int) -> bool:
# Check if the accounts exist and there is enough balance in account1
if 1 <= account1 <= len(self.balance) and 1 <= account2 <= len(self.balance) and self.balance[account1-1] >= money:
# Perform the transfer
self.balance[account1-1] -= money
self.balance[account2-1] += money
return True
return False
def deposit(self, account: int, money: int) -> bool:
# Check if the account exists
if 1 <= account <= len(self.balance):
# Perform the deposit
self.balance[account-1] += money
return True
return False
def withdraw(self, account: int, money: int) -> bool:
# Check if the account exists and there is enough balance
if 1 <= account <= len(self.balance) and self.balance[account-1] >= money:
# Perform the withdrawal
self.balance[account-1] -= money
return True
return False
|
This implementation ensures the constraints are met for the transactions, such as verifying account numbers and sufficient balances. If any transaction is invalid, it will return False
. The time complexity of each operation is (O(1)).