邻接矩阵
class Vertex:
def __init__(self, node):
self.id = node
# Mark all nodes unvisited
self.visited = False def addNeighbor(self, neighbor, G):
G.addEdge(self.id, neighbor) def getConnections(self, G):
return G.adjMatrix[self.id] def getVertexID(self):
return self.id def setVertexID(self, id):
self.id = id def setVisited(self):
self.visited = True def __str__(self):
return str(self.id) class Graph:
def __init__(self, numVertices=10, directed=False):
self.adjMatrix = [[None] * numVertices for _ in range(numVertices)]
self.numVertices = numVertices
self.vertices = []
self.directed = directed
for i in range(0, numVertices):
newVertex = Vertex(i)
self.vertices.append(newVertex) def addVertex(self, vtx, id): #增加点,这个function没有扩展功能
if 0 <= vtx < self.numVertices:
self.vertices[vtx].setVertexID(id) def getVertex(self, n):
for vertxin in range(0, self.numVertices):
if n == self.vertices[vertxin].getVertexID():
return vertxin
return None def addEdge(self, frm, to, cost=0): #返回全部连线/航线
#print("from",frm, self.getVertex(frm))
#print("to",to, self.getVertex(to))
if self.getVertex(frm) is not None and self.getVertex(to) is not None:
self.adjMatrix[self.getVertex(frm)][self.getVertex(to)] = cost
if not self.directed:
# For directed graph do not add this
self.adjMatrix[self.getVertex(to)][self.getVertex(frm)] = cost def getVertices(self):
vertices = []
for vertxin in range(0, self.numVertices):
vertices.append(self.vertices[vertxin].getVertexID())
return vertices def printMatrix(self):
for u in range(0, self.numVertices):
row = []
for v in range(0, self.numVertices):
row.append(str(self.adjMatrix[u][v]) if self.adjMatrix[u][v] is not None else '/')
print(row) def getEdges(self):
edges = []
for v in range(0, self.numVertices):
for u in range(0, self.numVertices):
if self.adjMatrix[u][v] is not None:
vid = self.vertices[v].getVertexID()
wid = self.vertices[u].getVertexID()
edges.append((vid, wid, self.adjMatrix[u][v]))
return edges def getNeighbors(self, n):
neighbors = []
for vertxin in range(0, self.numVertices):
if n == self.vertices[vertxin].getVertexID():
for neighbor in range(0, self.numVertices):
if (self.adjMatrix[vertxin][neighbor] is not None):
neighbors.append(self.vertices[neighbor].getVertexID())
return neighbors def isConnected(self, u, v):
uidx = self.getVertex(u)
vidx = self.getVertex(v)
return self.adjMatrix[uidx][vidx] is not None def get2Hops(self, u): #转一次机可以到达哪里
neighbors = self.getNeighbors(u)
print(neighbors)
hopset = set()
for v in neighbors:
hops = self.getNeighbors(v)
hopset |= set(hops)
return list(hopset)

邻接表
import sys
class Vertex:
def __init__(self, node):
self.id = node
self.adjacent = {}
#为所有节点设置距离无穷大
self.distance = sys.maxsize
# 标记未访问的所有节点
self.visited = False
# Predecessor
self.previous = None def addNeighbor(self, neighbor, weight=0):
self.adjacent[neighbor] = weight # returns a list
def getConnections(self): # neighbor keys
return self.adjacent.keys() def getVertexID(self):
return self.id def getWeight(self, neighbor):
return self.adjacent[neighbor] def setDistance(self, dist):
self.distance = dist def getDistance(self):
return self.distance def setPrevious(self, prev):
self.previous = prev def setVisited(self):
self.visited = True def __str__(self):
return str(self.id) + ' adjacent: ' + str([x.id for x in self.adjacent]) def __lt__(self, other):
return self.distance < other.distance and self.id < other.id class Graph:
def __init__(self, directed=False):
# key is string, vertex id
# value is Vertex
self.vertDictionary = {}
self.numVertices = 0
self.directed = directed def __iter__(self):
return iter(self.vertDictionary.values()) def isDirected(self):
return self.directed def vectexCount(self):
return self.numVertices def addVertex(self, node):
self.numVertices = self.numVertices + 1
newVertex = Vertex(node)
self.vertDictionary[node] = newVertex
return newVertex def getVertex(self, n):
if n in self.vertDictionary:
return self.vertDictionary[n]
else:
return None def addEdge(self, frm, to, cost=0):
if frm not in self.vertDictionary:
self.addVertex(frm)
if to not in self.vertDictionary:
self.addVertex(to) self.vertDictionary[frm].addNeighbor(self.vertDictionary[to], cost)
if not self.directed:
# For directed graph do not add this
self.vertDictionary[to].addNeighbor(self.vertDictionary[frm], cost) def getVertices(self):
return self.vertDictionary.keys() def setPrevious(self, current):
self.previous = current def getPrevious(self, current):
return self.previous def getEdges(self):
edges = []
for key, currentVert in self.vertDictionary.items():
for nbr in currentVert.getConnections():
currentVertID = currentVert.getVertexID()
nbrID = nbr.getVertexID()
edges.append((currentVertID, nbrID, currentVert.getWeight(nbr))) # tuple
return edges def getNeighbors(self, v):
vertex = self.vertDictionary[v]
return vertex.getConnections()

引入的这两段代码的原文链接:
https://www.cnblogs.com/kumata/p/9246502.html

Python实现数据结构 图的更多相关文章

  1. python 与数据结构

    在上面的文章中,我写了python中的一些特性,主要是简单为主,主要是因为一些其他复杂的东西可以通过简单的知识演变而来,比如装饰器还可以带参数,可以使用装饰类,在类中不同的方法中调用,不想写的太复杂, ...

  2. [0x00 用Python讲解数据结构与算法] 概览

    自从工作后就没什么时间更新博客了,最近抽空学了点Python,觉得Python真的是很强大呀.想来在大学中没有学好数据结构和算法,自己的意志力一直不够坚定,这次想好好看一本书,认真把基本的数据结构和算 ...

  3. (python数据分析)第03章 Python的数据结构、函数和文件

    本章讨论Python的内置功能,这些功能本书会用到很多.虽然扩展库,比如pandas和Numpy,使处理大数据集很方便,但它们是和Python的内置数据处理工具一同使用的. 我们会从Python最基础 ...

  4. Python入门神图

    国外某小哥制作的Python入门神图

  5. 【ZZ】Python入门神图

    http://mp.weixin.qq.com/s?__biz=MzA3OTIxNTA0MA==&mid=401383338&idx=1&sn=73009cce06d58656 ...

  6. Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET

    Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET Python -- 堆数据结构 heapq 分类: Python 2012-09 ...

  7. python实现数据结构单链表

    #python实现数据结构单链表 # -*- coding: utf-8 -*- class Node(object): """节点""" ...

  8. 《用Python解决数据结构与算法问题》在线阅读

    源于经典 数据结构作为计算机从业人员的必备基础,Java, c 之类的语言有很多这方面的书籍,Python 相对较少, 其中比较著名的一本 problem-solving-with-algorithm ...

  9. 数据结构--图 的JAVA实现(上)

    1,摘要: 本系列文章主要学习如何使用JAVA语言以邻接表的方式实现了数据结构---图(Graph),这是第一篇文章,学习如何用JAVA来表示图的顶点.从数据的表示方法来说,有二种表示图的方式:一种是 ...

随机推荐

  1. Angular2-------Error: Unexpected value ‘undefined’ declared by the module ‘模块名

    请检查[app.module.ts]文件中的[declarations]模块最后是否多了一个逗号 (完)

  2. Webapi管理和性能测试工具WebBenchmark

    WebBenchmark是一款基于开源通讯组件Beetlex扩展的Webapi管理和性能测试工具,在传统工具中一般管理工具缺乏性能压测能力或有性能测试的缺少管理功能:WebBenchmark的设计目标 ...

  3. SpringBoot+Mybatis一级缓存和二级缓存详解

    本文主要介绍在SpringBoot项目中如何使用Mybatis的一级.二级缓存,为了演示方便,本文的数据库采用H2内存数据库,数据库连接池默认使用SpringBoot2.X自带的hikariCP. 正 ...

  4. 一文说通Blazor for Server-Side的项目结构

    用C#代替Javascript来做Web应用,是有多爽?   今天聊聊 Blazor. Blazor 是一个 Web UI 框架.这个框架允许开发者使用 C# 来创建可运行于浏览器的具有完全交互 UI ...

  5. day09 基本数据类型(中)

    目录 一 列表(list) 1.作用 2.定义 3.类型转化 4.内置方法 4.1按索引取值 4.2切片 4.3长度 4.4成员运算 4.5往列表中加值 4.5.1追加 4.5.2追加列表 4.5.3 ...

  6. vue 实现滑块验证码

    图一为拖拽前效果,图二为拖拽后效果 一.新建文件JcRange.vue,代码如下: 1.模板代码: <template> <div class="jc-component_ ...

  7. Python 为什么只需一条语句“a,b=b,a”,就能直接交换两个变量?

    从接触 Python 时起,我就觉得 Python 的元组解包(unpacking)挺有意思,非常简洁好用. 最显而易见的例子就是多重赋值,即在一条语句中同时给多个变量赋值: >>> ...

  8. node -v node is not define

    安装node js  踩过的坑 应该是在CMD 命令里执行 node -v 我却傻傻的跑到 node.js 里执行 node -v 结果就报 node is not define 真相如下图!!!

  9. Python实现性能自动化测试的方法【推荐好文】

    1.什么是性能自动化测试? ◆ 性能 △ 系统负载能力 △ 超负荷运行下的稳定性 △ 系统瓶颈 ◆ 自动化测试 △ 使用程序代替手工 △ 提升测试效率 ◆ 性能自动化 △ 使用代码模拟大批量用户 △ ...

  10. Ethical Hacking - NETWORK PENETRATION TESTING(24)

    Detecting suspicious activities using Wireshark You can use make the MAC address of the router to st ...