Home > Blockchain >  Actually simple recursion problem on Python
Actually simple recursion problem on Python

Time:06-28

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

CodePudding user response:

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)
  • Related