Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Actually simple recursion problem on Python

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading