-
-
Save stephengruppetta/7f025d2a89d09db83c9d475f998babf0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Book: | |
def __init__(self, title, author, publication_year): | |
self.title = title | |
self.author = author | |
self.publication_year = publication_year | |
def __str__(self): | |
return f"{self.title} by {self.author} ({self.publication_year})" | |
def __repr__(self): | |
return f"Book('{self.title}', '{self.author}', {self.publication_year})" | |
class Library: | |
def __init__(self): | |
self.books = [] | |
def add_books(self, books): | |
""" | |
Add books to the library | |
:param books: list (or other sequence) of Book objects | |
""" | |
self.books.extend(books) | |
def __getitem__(self, item): | |
if isinstance(item, int): | |
return self.books[item] | |
elif isinstance(item, str): | |
matching_author = [ | |
book | |
for book in self.books | |
if item.casefold() in book.author.casefold() | |
] | |
matching_title = [ | |
book | |
for book in self.books | |
if item.casefold() in book.title.casefold() | |
] | |
return matching_author + matching_title | |
books_data = [ | |
Book("To Kill a Mockingbird", "Harper Lee", 1960), | |
Book("1984", "George Orwell", 1949), | |
Book("Animal Farm", "George Orwell", 1945), | |
Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979), | |
Book("Harry Potter and the Philosopher's Stone", "J.K. Rowling", 1997), | |
Book("Harry Potter and the Chamber of Secrets", "J.K. Rowling", 1998), | |
Book("A Brief History of Time", "Stephen Hawking", 1988), | |
Book("The Selfish Gene", "Richard Dawkins", 1976), | |
Book("Cosmos", "Carl Sagan", 1980), | |
Book("The Tale of Peter Rabbit", "Beatrix Potter", 1902), | |
] | |
gorgeous_library = Library() | |
gorgeous_library.add_books(books_data) | |
print(*gorgeous_library["Potter"], sep="\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment