2

Hi just wondering if anyone can tell me why this code isn't working It's giving an internal server error Thanks

@app.post("/removerouter/")
def removerouter(name: str):
    Graph.remove_node(name)
    return "success"

And this is the function inside Graph


class Graph:
    def __init__(self):
        self.nodes = []
        self.edges = []
    def remove_node(self, name):
        self.nodes.remove(name)
        for Edges in self.edges:
            if name in Edges:
                self.edges.remove(Edges)

1 Answers1

1

Based on the code that you posted, I would say that the issue is somehow related to how you remove your edge(s) in the for loop.

When you delete a list element using the remove()function in Python, it changes the remaining element's indexing. For more details and alternatives, see this SO question.

I also don't understand why you are using an iterator variable called Edges in your for loop. Python variables shall always start with a lowercase letter in order not to clash with any existing (or future) class name.

I would rather do something like this:

class Graph:
    def __init__(self):
        self.nodes = []
        self.edges = []

    def remove_node(self, name):
        self.nodes.remove(name)
        self.edges = [edge for edge in self.edges if name not in edge] 

Note that I'm using a list comprehension here to assign a new list to self.edges.

If you want to avoid list comprehension, you could also keep your for loop and first store the indexes of the edges that need to be removed. Then, for each index, you can simply do del self.edges[index].

Antoine
  • 1,393
  • 4
  • 20
  • 26