【问题标题】:trying to use the getBooksByAuthor method to return all the books from that author in the Linked List called BookCollection尝试使用 getBooksByAuthor 方法从名为 BookCollection 的链接列表中返回该作者的所有书籍
【发布时间】:2021-12-20 22:58:21
【问题描述】:

具有以下属性的书籍对象:标题、作者、年份

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

名为BookCollection的链表:

class BookCollection():
    def __init__(self):
        self.head = None
    def insertBook(self, book)
        temp = BookCollectionNode(book)
        temp.setNext(self.head)
        self.head = temp

试图归还某个作者的所有书籍

    def getBooksByAuthor(self, author):
        b = Book()
        if author == b.getAuthor():
            return b.getBookDetails

名为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

使用下面的函数来使用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"))

尝试使用此方法获取所有斯蒂芬金斯的书籍。应返回 b0b1b3

【问题讨论】:

    标签: python linked-list getmethod


    【解决方案1】:

    getBooksByAuthor 有问题。你为什么要在里面创作一本新书?此外,您没有在其中使用self,这意味着您实际上并没有在查看您收藏的书籍。

    通常,当您不在方法中使用self 时,要么是因为您希望您的方法返回一个常量(这可能会发生),要么是因为您出错了。

    因此,您需要循环访问您收藏的书籍:

        def getBooksByAuthor(self, author):
            node = self.head
            result = list()  # list of book details with the given author
            while node is not None:  # loop on the nodes the collection
                book = node.getData()
                if book.getAuthor() == author:
                    result.append(book.getBookDetails())
                node = node.getNext()  # move to the next book of the collection
            return result
    

    使用修改后的getBooksByAuthor 输出(并在您的收藏中添加b1,您忘记了):

    ['Title: Rage, Author: King, Stephen, Year: 1977', 'Title: The Shining, Author: King, Stephen, Year: 1977', 'Title: Cujo, Author: King, Stephen, Year: 1981']
    

    【讨论】:

      猜你喜欢
      • 2013-10-19
      • 2014-06-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多