#πŸ”’ How do i rewrite this recursive function iteratively?

25 messages Β· Page 1 of 1 (latest)

solar beacon
#
    def get_paths(
            self, tank: str, /, *, _grapth: dict | None = None, _path: tuple = ()
            ) -> Generator[list[str], None, None]:
        """
        # Generator Method

        returns a list which contains lists for every path to the tank

        ("triplex") ->  [["basic", "twin", "helix", "triplex"], ["basic", "desmos", "helix", "triplex"]]

        """
        grapth = _grapth
        path = _path

        if grapth is None:
            grapth = self.tree
        

        for key, leaf in grapth.items():
            # print(f"New call: {key=}\n{leaf=}")
            if key == tank:
                # print(f"key is tank, path: {[*path, tank]}, {key=}")
                yield [*path, tank]

            elif isinstance(leaf, list):
                if tank in leaf:
                    # print(f"Found tank in {leaf}, path: {[*path, tank]}")
                    yield [*path, key, tank]

            elif isinstance(leaf, dict):
                # print(f"Creating a new recursion call...\n{tank, leaf, path + (key,)}")
                yield from self.get_paths(tank, _grapth=leaf, _path=(path + (key,)))
cobalt forgeBOT
#

@solar beacon

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

meager zealot
#

yo u on ur own dude

#

what the hell is that

pallid oak
#

why do you want to rewrite it?

meager zealot
pallid oak
#

they have kind of a progression-tree for a game, and are finding all paths you can take in it to reach a certain point

solar beacon
#

its horrible

pallid oak
#

its not

solar beacon
#

and i wish there was a way to not

pallid oak
#

the iterative version will not be strictly better or easier to read. recursion is natural for trees and graphs.

solar beacon
#

have to wrap it or add user unused arguments

#

i am trying to rewrite it with ts thats why i got back to it

pallid oak
#

generally, you rewrite recursion to iteration by using a stack
here, you'd have a stack of the trees/graphs, start with the root, and until the stack is empty - do the path finding. when you would previously recur over a path - push it to the stack

hearty yacht
solar beacon
#

i guess typescript makes it easier to wrap with protected/private since i can hide it

stark elm
#

The iterative way will probably look very similar, just with an extra loop, and another list to act as a stack. I doubt it would be an improvement.

pallid oak
#

yeah

stack = [(root, ())]
while stack:
    graph, path = stack.pop()
    for key, leaf in graph.items():
        if key == tank:
            yield [*path, tank]
        elif isinstance(leaf, list):
            if tank in leaf:
                yield [*path, key, tank]
        elif isinstance(leaf, dict):
            stack.append((leaf, path + (key,)))
solar beacon
#

honestly this looks cleaner

#

ooooo :3

#

im gonna try this!

cobalt forgeBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.