Python Forum
Delete edge between 2 vertex in graph problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Delete edge between 2 vertex in graph problem
#1
Hello Python community,

I am new to python and it is my first post. I wanted to make a graph describing nodes (vertex) and edges. I could easily add nodes and edges from the graph. But whenever I try to delete an edge, it is not working properly. Below is my code. The problem comes from the remove_edge method which when it calls the find_edge method, I am getting new Vertices created instead of the ones I have already inserted.
Could anyone help me try to solve this issue?

Thanks in advance for anyone who goes through the code. Heart Heart Heart

import networkx as nx
import matplotlib as plt
###############################################################################
# Class Vertex
###############################################################################
class Vertex:
def __init__(self, value): # Init method called whenever Vertex instance encountered
self.value = value # Vertex has a value property
self.edges = {} # Vertex has edges property stored in a dictionary

###############################################################################
def __eq__(self, other): # Used to compare == equality between different Vertex objects
return self.value == other.value # Returns "True" if both Vertex objects are same
###############################################################################

def __hash__(self):
return int(self.value)

def degree(self): # degree method returns the number of edges
return len(self.edges)

def __str__(self): # __str__ method used to return a string
return str(self.value)

def __repr__(self): # __repr__ method used by developers for debugging
return "Vertex({})".format(repr(self.value))

###############################################################################
# Class Edge
###############################################################################


class Edge:
def __init__(self, v, w): # Class Edge has two vertices v and w
self.v = v # Edge has Vertex v property
self.w = w # Edge has Vertex w property

def other(self, v): # other gives the other vertex of an edge
if v == self.v: # If vertex v, then give vertex w
return self.w
elif v == self.w: # If vertex w, then give vertex v
return self.v
else:
raise # raises Error or smg like that...

def __str__(self): # __str__ method used to return a string
return "<Edge between vertex {} and vertex {}>".format(str(self.v), str(self.w))

def __repr__(self): # __repr__ method used by developers for debugging
return "Edge({}, {})".format(repr(self.v), repr(self.w))

###############################################################################
# Class Graph
###############################################################################

class Graph:
def __init__(self): # Class Graph has vertices and edges
self.vertices = [] # Initial Graph's vertices property set to an empty list
self.edges = [] # Initial Graph's edges property set to an empty list

def find_vertex(self, value):
for vertex in self.vertices:
if vertex.value == value:
return vertex
return None
#====================================================================
[b]
@classmethod
def find_edge(self,v, w): # find_edge used to return wth element of edges for v in dictionary
if w in v.edges: # Looking for Vertex 'w' in Vertex v.edges dictionary and if present
return v.edges[w] # Return Vertex v.edges[w]- i.e accessing key 'w' in the v.edges dictionary
else: # If no edges found for v, return None
return None
[/b]
#====================================================================
def add_edge(self, v, w): # Adds edge between two vertices
edge = self.find_edge(v, w) # Goes to find_edge to see if there is an edge bw the 2 vertices
if not edge: # If there is no edge between the 2 vertices,
edge = Edge(v, w) # Make an edge between the 2 vertices
v.edges[w] = edge # Creating a key 'w' in v.edges dictionary and assigning value edge to it
w.edges[v] = edge # Creating a key 'v' in w.edges dictionary and assigning value edge to it
# This means that for Vertex v and w's property 'edges', which is initially an empty dictionary, we create a key with
# the other vertex as key (i.e. w for v and vice versa) and assign Edge(v, w) to both objects' values for each key
self.edges.append(edge) # Append the edge to the graph self.edges list

###############################################################################

def remove_edge(self, v, w): # Removes the edge between two vertices
[b] edge = self.find_edge(v, w) # Goes to find_edge to see if there is an edge bw the 2 vertices ##### GETTING NONE HERE #####[/b]
if edge: # If there is an edge
del v.edges[w] # Delete the wth element of edges in v
del w.edges[v] # Delete the vth element of edges in w
self.edges.remove(edge) # Remove "edge" from graph's self.edges

def add_vertex(self, vertex): # Adding a vertex implies adding it to the graph's self.vertices list
self.vertices.append(vertex)

def remove_vertex(self, vertex): # Removing a vertex
for w in vertex.edges: # Iterate over that vertex's edges
edge = vertex.edges[w] # Pass the vertex edges to the variable "edge"
self.edges.remove(edge) # Remove "edge" from Graph's self.edges list
del w.edges[vertex] # Delete all edges of vertex with [vertex] as index
vertex.edges = [] # The passed vertex's edges are reinitialized to None
self.vertices.remove(vertex) # Remove vertex from graph's list of vertices

def clone(self):
g = Graph()
for vertex in self.vertices:
g.add_vertex(Vertex(vertex.value))
for edge in self.edges:
g.add_edge(g.find_vertex(edge.v.value), g.find_vertex(edge.w.value))
return g

def __str__(self): # __str__ method used to return a string
return '\n'.join([str(x) for x in
["Graph {"] + self.vertices + self.edges + ["}"]])
###############################################################################

def main():

g = Graph()
g.add_vertex(Vertex("0"))
g.add_vertex(Vertex("1"))
g.add_vertex(Vertex("2"))
g.add_vertex(Vertex("3"))
g.remove_vertex(Vertex('0'))

g.add_edge(Vertex('0'), Vertex('1'))

###############################################################################
[b]g.remove_edge(Vertex('0'), Vertex('1'))[/b]
###############################################################################
print(g)



main()
Reply
#2
Hello guys, i'm really having difficulty with my R-Programming assignment.

Task:
After months of cajoling, you have persuaded ornithologists from three institutions in DC to agree to share their data on bird sightings as part of a collaborative project. You’ve now received data from these collaborators, and need to clean and combine the data and produce a map for the time period interest.
Steps:
Read in and combine the data
Reformat all data format into decimal degrees
Remove and clean any erroneous values
Filter points to include just those taken on or after Jan, 1st, 2010
Filter points to include only those taken during transect surveys
Use the map_template.R script to plot the final set of cleaned and filtered points over a map of DC



I imported the files and used "rbind" to put them together but I would like to first clean each of them before binding them together. I tried to format the dates but I get 'NA' eventually because the vectors are probably different somewhere in the data.
I used the "measurement" package to convert the decimal-minutes to decimal-degrees but I get "NA" too.
here is part of the code:
firstfile$Longitude = gsub('W', '', firstfile$Longitude)
firstfile$Longitude = gsub('""', '', firstfile$Longitude)
firstfile$Longitude = measurements::conv_unit(firstfile$longitude, from = 'deg_dec_min', to = 'dec_deg')
Thank you for your help
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to used the edge detection in opencv python to return number of edge? Vivian 2 2,720 May-04-2018, 08:31 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020