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,)))
#π How do i rewrite this recursive function iteratively?
25 messages Β· Page 1 of 1 (latest)
@solar beacon
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.
Closes after a period of inactivity, or when you send !close.
why do you want to rewrite it?
what's that code even abt dawg
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
i think the message above speaks for itself
its horrible
its not
and i wish there was a way to not
the iterative version will not be strictly better or easier to read. recursion is natural for trees and graphs.
have to wrap it or add user unused arguments
i am trying to rewrite it with ts thats why i got back to it
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
i use all arguments fytb
i guess typescript makes it easier to wrap with protected/private since i can hide it
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.
ok
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,)))
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.