1

During coding I came across with this simple recursion problem and I wrote an example of my code below. I ask somebody to find a good way to solve the problem. I guess it is supposed to write third class containing the relations.

from __future__ import annotations

from typing import Set


class Author:

    def __init__(self):
        self.books: Set[Book] = set()

    def add_book(self, book: Book):
        self.books.add(book)
        book.add_author(self)


class Book:

    def __init__(self):
        self.authors: Set[Author] = set()

    def add_author(self, author: Author):
        self.authors.add(author)
        author.add_book(self)

author = Author()
book = Book()
author.add_book(book) #RecursionError: maximum recursion depth exceeded while calling a Python object

Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
  • 1
    `Author.add_book()` calls `book.add_author()`. `Book.add_author()` calls `author.add_book()`. This is an infinite loop. – Barmar Jun 27 '22 at 21:12
  • @Barmar yep. I need to keep the relation between author and book **unbroken**, that's why I wrote this – numericmaestro Jun 27 '22 at 21:17

1 Answers1

3

The add_book() and add_author() methods call each other, so you get into an infinite loop.

The methods should check whether they're already added and not do anything, this will stop the recursion.

class Author:

    def __init__(self):
        self.books: Set[Book] = set()

    def add_book(self, book: Book):
        if book not in self.books:
            self.books.add(book)
            book.add_author(self)


class Book:

    def __init__(self):
        self.authors: Set[Author] = set()

    def add_author(self, author: Author):
        if author not in self.authors:
            self.authors.add(author)
            author.add_book(self)
Barmar
  • 741,623
  • 53
  • 500
  • 612