Editor

Library Lending Desk

#631 · Dictionaries and sets · Intermediate · Mini-project · 170 XP · about 60 min

Build the lending desk of a small library. The library is a dictionary that maps each title to a record of how many copies it owns and who has borrowed them, for example {'Dune': {'copies': 2, 'out': ['Mia']}}: one copy of Dune is with Mia and one is on the shelf. out lists the borrowers in the order they took the book.

Parts

  • Part 1 add_copies(library, title, count): add count copies of a title. A new title starts as {'copies': 0, 'out': []}. Return the number of copies the library now owns of that title.
  • Part 2 borrowed_by(library, member): a list of the titles the member has borrowed, in alphabetical order.
  • Part 3 lend(library, title, member): try to lend a copy. Check these in order and return the first that applies: 'unknown title' if the library does not have the title, 'already borrowed' if the member has a copy of it already, 'limit reached' if the member already has 3 books out, 'none left' if every copy is out. Otherwise add the member to the end of out and return 'ok'.
  • Part 4 give_back(library, title, member, days): the member returns the title after keeping it days days. Take them off out and return the late fee in cents: books are lent for 14 days, every day after that costs 25 cents, and the fee is never more than 500 cents. If the member does not have that title, change nothing and return None.
  • Part 5 available(library): a list of (title, copies_on_the_shelf) tuples for the titles with at least one copy on the shelf, in alphabetical order of title.

Examples

library = {}
add_copies(library, 'Dune', 1)     # returns 1
add_copies(library, 'Emma', 2)     # returns 2
lend(library, 'Dune', 'Mia')       # returns 'ok'
lend(library, 'Dune', 'Leo')       # returns 'none left'
borrowed_by(library, 'Mia')        # returns ['Dune']
available(library)                 # returns [('Emma', 2)]
give_back(library, 'Dune', 'Mia', 17)   # returns 75

Mia kept Dune for 17 days, 3 days more than the 14 allowed, so she pays 3 x 25 = 75 cents.

Constraints

  • A library has at most 1,000 titles, and count and days are whole numbers of 0 or more.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.