-1
    def search(self, string):
        result = ""
        if len(string) >= 4:
            for book in self.collection:
                if (string.lower() in book.get_title().lower):
                    result += str(book)
            return result

I have a library class which has library.collection as a list of book objects, now I want to search the "string" and return the book I want, above are my code. the book class has method get_title() which returns the "title" of the book adn str(book) returns a string"book id: book title"

this works well, for example when I search "under" i got

    10: Under the Net
    11: Under the Net
    117: Under the Skin

but I have two copies of the book "under the net"

I just want to find one of them, so for every string I search, if there are several copies of a book, I just want to add one of the str(book) to my result. can anyone help me with this?

Sally
  • 87
  • 2
  • 10

1 Answers1

-1

Use a set instead of a string for results. Sets don't allow duplicates, and it's faster to add elements to a set than to append to a string. You can use join to create a string at the end if that's what you want.

def search(self, string):
    results = set()
    if len(string) >= 4:
        for book in self.collection:
            if (string.lower() in book_title.get_title().lower):
                results.add(str(book))
        return "".join(results)
jpkotta
  • 9,237
  • 3
  • 29
  • 34
  • but the thing is each book has a unique id..so even they are the same book, they have different ids – Sally Mar 03 '17 at 20:54
  • `book_title.get_title().lower` isn't gonna cut it. – Jean-François Fabre Mar 03 '17 at 20:55
  • 1
    and it will return the joined list of all results without space: hardly useful. You haven't tested that, it can't be (well, you trusted the OP code, but it's wrong) – Jean-François Fabre Mar 03 '17 at 20:57
  • cause the str(book) returns a string "book id: book title" so the two books are not duplicates in the set as their ids are different – Sally Mar 03 '17 at 20:59
  • @Vicky So instead of `str(book)`, add `book.get_title()` to the set. If you care about preserving the id as well, then use a dict with book titles as keys and lists of ids as values. – jpkotta Mar 04 '17 at 22:32