Book Object with attributes: Title, Author, Year
class Book():
def __init__(self, title = "", author = "", year = None):
self.title = title
self.author = author
self.year = year
def getTitle(self):
return self.title
def getAuthor(self):
return self.author
def getYear(self):
return self.year
def getBookDetails(self):
string = ("Title: {}, Author: {}, Year: {}"\
.format(self.title, self.author, self.year))
return string
Linked List called BookCollection:
class BookCollection():
def __init__(self):
self.head = None
def insertBook(self, book)
temp = BookCollectionNode(book)
temp.setNext(self.head)
self.head = temp
Trying to return all the books by a certain author
def getBooksByAuthor(self, author):
b = Book()
if author == b.getAuthor():
return b.getBookDetails
Node class called BookCollectionNode:
class BookCollectionNode():
def __init__(self, data):
self.data = data
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newData):
self.data = newData
def setNext(self, newNext):
self.next = newNext
Using the functions below to use the getBooksByAuthorMethod:
b0 = Book("Cujo", "King, Stephen", 1981)
b1 = Book("The Shining", "King, Stephen", 1977)
b2 = Book("Ready Player One", "Cline, Ernest", 2011)
b3 = Book("Rage", "King, Stephen", 1977)
bc = BookCollection()
bc.insertBook(b0)
bc.insertBook(b2)
bc.insertBook(b3)
print(bc.getBooksByAuthor("King, Stephen"))
Trying to get all of Stephen Kings books by using this method. Should return b0, b1, and b3.
There is a problem in
getBooksByAuthor. Why do you create a new book in it? Also you don't useselfin it which means that you're actually not looking at the books of your collection.Usually, when you do not use
selfin a method, it's either because you want your method to return a constant (which can happen) either because you made an error.So you need to loop on the books of your collection:
Output with the modified
getBooksByAuthor(and with addingb1in your collection, which you forgot):