254. Python Program to Lend and Return Library Books
MediumPhase 2 · Practice
A few steps again, with tools you know: a while loop, split() and a dictionary with values().
Overview
A library must always know which books are out and who has them. A dictionary that links each book to a reader does exactly that.
Problem Statement
Leila helps at a small library. At the start, every book is on the shelf. Each reader may have at most 2 books at a time. Read one command per line until a line says end. The commands are:
lend <book> <name>: check these in order, and do only the first one that fits:- Someone has the book now: print
<book> is not available. - The reader has 2 books now: print
<name> already has 2 books. - Otherwise, lend the book to the reader and print
<name> borrowed <book>.
- Someone has the book now: print
return <book>: the book comes back to the shelf: print<book> is back. If the book is not out, print<book> was not lent.who <book>: print<book> is with <name>if the book is out, or<book> is on the shelfif it is not.
For any other command, print Unknown command. Print nothing for end. Book titles and names must match exactly: Hamlet and hamlet are different books.
Examples
Example 1. Input:
lend Dune Ama
lend Emma Ama
who Dune
lend Dune Raj
return Dune
who Dune
lend Dune Raj
end
gives:
Ama borrowed Dune
Ama borrowed Emma
Dune is with Ama
Dune is not available
Dune is back
Dune is on the shelf
Raj borrowed Dune
Why: Raj cannot have Dune while Ama has it. After Ama returns Dune, Raj can borrow it.
Example 2. Input:
lend Heidi Ola
lend Hamlet Ola
lend Matilda Ola
return Matilda
renew Heidi
end
gives:
Ola borrowed Heidi
Ola borrowed Hamlet
Ola already has 2 books
Matilda was not lent
Unknown command
Why: Ola already has 2 books, so Ola cannot borrow Matilda. Matilda was never lent, so it cannot be returned. renew is not a command.
Input
One command per line, with one space between the parts. Book titles and names are one word each, like Dune or Matilda. The last line is always end. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line for each command. The tests try 7 different inputs, also a reader with 2 books who asks for a book that is out, a book returned twice and different capital letters.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.