Problem 458172 · easy · Level 04 Non-Linear Data Structures

Accounts With Their Own History

py-classes · state and behaviour · instances

A small credit union keeps one account per member. Every account has an owner, a balance in whole euros and a history of what happened to it. Write a class Account:

  • Account(owner, balance=0) opens an account. Its history starts with the entry ("open", balance, balance).
  • deposit(amount) adds amount and returns the new balance. An amount that is not positive raises ValueError and changes nothing.
  • withdraw(amount) takes amount out and returns True, or returns False and changes nothing if the balance is too small. A non-positive amount raises ValueError.
  • transfer_to(other, amount) moves money to the account other, with the same rules as withdraw, and returns True or False.
  • history() returns a new list of the entries so far, oldest first.
  • The attributes owner and balance can be read directly.

Every change that succeeds adds one entry (kind, amount, balance_after) to the history of each account it touches: the kinds are "deposit", "withdraw", "transfer out" and "transfer in". Refused withdrawals and transfers leave no entry.

The tests run a whole day at the bank with the helper bank_day(Account, script). Each step of the script is a tuple: ("open", name, balance), ("deposit", name, amount), ("withdraw", name, amount), ("transfer", from_name, to_name, amount), ("balance", name) or ("history", name). It returns one result per step (None for "open", and the name of the exception if a method raises one). You can call it with Run.

Examples

Input:  bank_day(Account, [("open", "ada", 50), ("open", "bo", 0),
                           ("deposit", "ada", 20), ("withdraw", "bo", 5),
                           ("transfer", "ada", "bo", 30), ("history", "bo")])
Output: [None, None, 70, False, True,
         [("open", 0, 0), ("transfer in", 30, 30)]]

Input:  bank_day(Account, [("open", "cy", 10), ("deposit", "cy", 0), ("balance", "cy")])
Output: [None, "ValueError", 10]

Constraints

  • Amounts and balances are whole numbers; up to 2000 steps and 50 accounts per day.
  • Changing one account never changes another, except through transfer_to.

Goals

  • Write a class whose objects each keep their own attributes
  • Keep a balance and a history consistent by changing them only inside methods
  • Avoid the class-level list that every object would share
Starting Python…