Recursive method for a multilinked structure

  python

I have this class in python which accepts two hash and links them together. What I want is to be able to recursively fetch all linked hashes, however I’m struggling to write a correct recursive function.
What I have so far:

class MultiLink:
    def __init__(self):
        self.map = {}

    def get(self, md5: str, scanned: list = None) -> list:
        matches = []
        scanned = scanned or []
        for match in self.map[md5]:
            matches.append(match)

            if match in scanned:
                continue

            scanned.append(match)
            for mmatch in self.map[match]:
                if mmatch not in scanned:
                    matches += self.get(mmatch, scanned=scanned)

        return list(set(matches))

    def link(self, first: str, second: str) -> None:
        try:
            self.map[first].append(second)
        except KeyError:
            self.map[first] = [second]

        try:
            self.map[second].append(first)
        except KeyError:
            self.map[second] = [first]

As you can see the output does not perform as I expect it to:

l = MultiLink()
l.link("a","b")
l.link("b", "c")
l.link("c", "a")
l.get("c")

This outputs ['c', 'b', 'a'], but l.get("a") outputs ['c', 'b'].

If I then do l.link("d", "a"), it returns ['c', 'a'] instead of the whole set of results.

This is my first attempt at writing something like this, so I’m sure I’m making a very stupid error somewhere, but I cannot find it by myself. Does anyone know how to make this work? Or if there’s already an implementation of this somewhere? I checked the collections module but I found nothing of interest there.

Source: Python Questions

LEAVE A COMMENT