Creating an adjacency list class in Python

2024/11/15 15:38:13

I was wondering how to create an adjacency list class

Here is what I have so far:


class AdjNode:def __init__(self, value):self.vertex = valueself.next = Noneclass Graph:def __init__(self):# Add edgesdef add_edge(self, u, v):node = AdjNode(v)node.next = self.graph[u]self.graph[u] = node
Answer

Here is a very verbose example; not exactly what you want, but I feel it's a start, and as mentioned in the comments, uses a standard list.

I think you should look into classes further and attempt to understand OOP; I think you'd be doing yourself an injustice by not understanding what is being asked but rather asking what is being asked. - JUST MY OPINION

class Graph:def __init__(self):self.graph = {}def addEdge(self, u, v):if u in self.graph:self.graph[u].append(v)else:self.graph[u] = [v]def deleteEdge(self, u, v):if u in self.graph:if v in self.graph[u]:self.graph[u].remove(v)else:print("Edge doesn't exist")else:print("Edge doesn't exist")def getNeighbors(self, u):return self.graph[u]def isAdjacent(self, u, v):if u in self.graph:if v in self.graph[u]:return Trueelse:return Falseelse:return Falsedef printGraph(self):print(self.graph)g = Graph()
g.addEdge(1, 2)
g.addEdge(1, 3)
g.addEdge(2, 3)
g.addEdge(2, 4)
g.addEdge(3, 4)
g.addEdge(3, 5)
g.addEdge(4, 5)
g.addEdge(5, 6)
g.addEdge(5, 7)
g.addEdge(6, 7)
g.printGraph()
print(g.getNeighbors(1))
print(g.isAdjacent(1, 2))
print(g.isAdjacent(1, 5))
print(g.isAdjacent(5, 6))
g.deleteEdge(1, 2)
g.deleteEdge(1, 5)
g.printGraph()

Output:

{1: [2, 3], 2: [3, 4], 3: [4, 5], 4: [5], 5: [6, 7], 6: [7]}
[2, 3]
True
False
True
Edge doesn't exist
{1: [3], 2: [3, 4], 3: [4, 5], 4: [5], 5: [6, 7], 6: [7]}
https://en.xdnf.cn/q/119644.html

Related Q&A

How can I separate a rust library and the pyo3 exported python extensions which wrap it

I have a rust library which provides useful functionality for use in other rust programs. Additionally I would like to provide this functionality as a python extension (using pyo3 and setuptools-rust, …

how do I count unique words of text files in specific directory with Python? [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Python convert path to dict

I have a list of paths that need to be converted to a dict ["/company/accounts/account1/accountId=11111","/company/accounts/account1/accountName=testacc","/company/accounts/acc…

Python: How to download images with the URLs in the excel and replace the URLs with the pictures?

As shown in the below picture,theres an excel sheet and about 2,000 URLs of cover images in the F column. What I want to do is that downloading the pictures with the URLs and replace the URL with the…

I cant figure out pip tensorrt line 17 error

I couldnt install it in any way, I wonder what could be the cause of the error. I installed C++ and other necessary stuff I am using windows 11 I installed pip install nvidia-pyindex with no problem. S…

Extracting specific values for a header in different lines using regex

I have text string which has multiple lines and each line has mix of characters/numbers and spaces etc. Here is how a couple lines look like:WEIGHT VOLUME CHA…

Creating a function to process through a .txt file of student grades

Can someone help...My driver file is here:from functions import process_marks def main():try:f = open(argv[1])except FileNotFoundError:print("\nFile ", argv[1], "is not available")e…

Python Reddit PRAW get top week. How to change limit?

I have been familiarising myself with PRAW for reddit. I am trying to get the top x posts for the week, however I am having trouble changing the limit for the "top" method. The documentatio…

I want to convert string 1F to hex 1F in Python, what should I do?

num="1F" nm="1" nm1="2" hex(num)^hex(nm)^hex(nm1)I wrote it like the code above, but hex doesnt work properly. I want to convert the string to hexadecimal, and I want an x…

How to call a function in a Django template?

I have a function on my views.py file that connects to a mail server and then appends to my Django model the email addresses of the recipients. The script works good. In Django, Im displaying the model…