Skip to content

Suggestion: a method to get a node index by a unique value #1457

Open
@abgros

Description

@abgros

Consider a graph like this:

graph = rx.PyDiGraph()
graph.add_node("a")
graph.add_node("b")
graph.add_node("c")

Say I want to find out what index the value b is at. The naïve implementation looks like:

def index_of(graph, value):
    return next((i for i in graph.node_indices() if graph[i] == value), None)

This is obviously very inefficient since it does a linear search across the entire graph. Instead, what I tend to do is create a separate hashmap which maps values to indices. This hashmap needs to be updated every time a node is added or removed from the graph. Also, we have to make sure that no duplicate nodes are added to the graph. It would be nice if rustworkx had a built-in way to do this. For example:

graph = rx.PyDiGraph(unique_values = True)
graph.add_node("a")
graph.add_node("b")
graph.add_node("c")
print(graph.index_of("b")) # 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions