Skip to content
ExamSpine

Write it

Copies left

A functionPython or Java11 tests, 7 of them hidden

On a phone? Put the lines in order instead

A school library keeps a Book object for each title. Its mutator methods refuse a change that would make the number of copies on the shelf impossible. Write a function that works out the same thing from simple data: it is given how many copies of a book the library owns, all on the shelf at the start, and a list (an array in Java) of actions, carried out in order. It returns how many copies are on the shelf after the last action.

  1. "borrow" takes one copy off the shelf, but only if at least one copy is there. Otherwise it is refused and changes nothing.
  2. "return" puts one copy back, but only if fewer than total copies are on the shelf. Otherwise it is refused and changes nothing.
  3. Any other text, such as "renew", changes nothing. Capital letters matter: "Borrow" is not "borrow".
  4. total is a whole number from 0 to 50. There are at most 50 actions, and the list can be empty.

Only the number your function returns is checked.

def copies_left(total: int, actions: list[str]) -> int

Examples

Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.

  • copies_left(3, ["borrow", "borrow", "return"]) should return 2: two copies out, one back (rules 1 and 2)
  • copies_left(1, ["borrow", "borrow"]) should return 0: the second borrow is refused, because the shelf is empty (rule 1)
  • copies_left(2, ["return"]) should return 2: a return is refused, because every copy is already on the shelf (rule 2)
  • copies_left(2, ["borrow", "renew"]) should return 1: renew is not a return, so it changes nothing (rule 3)

public static int copiesLeft(int total, String[] actions)

Checking whether Java answers can run here.

Examples

Your function is tested on 11 cases: the 4 examples below, and 7 hidden ones that check the rules above.

  • copiesLeft(3, new String[]{"borrow", "borrow", "return"}) should return 2: two copies out, one back (rules 1 and 2)
  • copiesLeft(1, new String[]{"borrow", "borrow"}) should return 0: the second borrow is refused, because the shelf is empty (rule 1)
  • copiesLeft(2, new String[]{"return"}) should return 2: a return is refused, because every copy is already on the shelf (rule 2)
  • copiesLeft(2, new String[]{"borrow", "renew"}) should return 1: renew is not a return, so it changes nothing (rule 3)
solution.pySolution.java