vendredi 3 janvier 2020

Pythonic DFS function to reduce duplicate patterns

The following is a generic DFS in python over a nested dictionary structure.

def dfs(d: dict):
    stack = []
    [stack.append([key]) for key in d]

    while stack:
        key_seq = stack.pop()
        content = get_by_path(d, key_seq)

        if isinstance(content, dict):
            [stack.append(key_seq + [key]) for key in content]
        else:
            print(content)

# utilities

def get_by_path(root: dict, items: list) -> any:
    """Access a nested object in root by item sequence."""
    return reduce(operator.getitem, items, root)

def set_by_path(root: dict, items: list, value: any) -> None:
    """Set a value in a nested object in root by item sequence."""
    get_by_path(root, items[:-1])[items[-1]] = value

For my current project, I have had to write several DFS algorithms, each of which are slightly different. Sometimes I want to construct a new dictionary, and other times I want to adjust the current dictionary. Is there any way for me to make the function more general, to reduce code reuse? Perhaps there are cool decorator tricks?

Any advice on making more general code to reduce code duplication would be helpful. Thank you.

Aucun commentaire:

Enregistrer un commentaire