Skip to content

Instantly share code, notes, and snippets.

@Armen-Jean-Andreasian
Created April 23, 2024 08:14
Show Gist options
  • Save Armen-Jean-Andreasian/ea654609cc433d537c484b905d94af6a to your computer and use it in GitHub Desktop.
Save Armen-Jean-Andreasian/ea654609cc433d537c484b905d94af6a to your computer and use it in GitHub Desktop.
Library Problem [Non-ordinary Solution]
class Book:
def __init__(self, title, genre):
self.title = title
self.genre = genre
class LibraryShelves(dict):
def add_shelf(self, new_genre: str):
"""Adds a new shelf to library"""
if new_genre not in self:
self[new_genre] = list()
return self
def remove_shelf(self, genre: str):
"""Removes the shelf from library. if it exists"""
if genre in self:
self.pop(genre)
return self
class Library:
__instances = dict()
def __new__(cls, *args, **kwargs):
library_name = kwargs.get('library_name')
if library_name not in cls.__instances:
new_instance = super().__new__(cls)
cls.__instances[library_name] = new_instance
return new_instance
else:
return cls.__instances[library_name]
def __init__(self, library_name: str):
if not hasattr(self, 'shelves'):
self.shelves = LibraryShelves()
self.library_name = library_name
def add_book(self, book: Book):
book_genre = book.genre
if book_genre in self.shelves:
self.shelves[book_genre].append(book)
else:
self.shelves[book_genre] = [book]
return self
def add_books(self, books: list[Book]):
for book in books:
self.add_book(book=book)
return self
@property
def get_all_books(self) -> dict:
return self.shelves
def get_books_by_genra(self, genra: str) -> list:
return self.shelves[genra] if genra in self.shelves else []
if __name__ == '__main__':
book1 = Book(title="Harry Potter", genre="Fantasy")
book2 = Book(title="Lord of the rings", genre="Fantasy")
ny_library = Library(library_name="New York National Library")
tokyo_library = Library(library_name="Tokyo National Library")
ny_library.add_books([book1, book2])
tokyo_library.add_book(book1)
duplicate_ny_library = Library(library_name="New York National Library")
print(ny_library.get_all_books) # dict[str:list[Book, Book]]
print(tokyo_library.get_all_books) # dict[str:list[Book]]
print(id(duplicate_ny_library) == id(ny_library)) # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment