- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我一直在尝试为流行的 kevin bacon 游戏创建图形表示。我已经创建了图形和顶点类,但在创建广度优先搜索方法来遍历图形并找到从 Kevin Bacon 到 Actor 的最短路径并在途中打印出边时遇到了一些麻烦。用户应该输入一个 Actor ,程序应该找到从 kevin bacon 到那个 Actor 的最短路径。然后用户将继续输入 Actor ,将采用到该 Actor 的最短路径,并打印出 kevin bacon 编号,否则将打印出 none。
有一个顶点和图形类。顶点类是一个字典,其中包含它所连接的其他顶点和边。
我正在处理的数据如下所示:
顶点:
[“凯文培根”、“ Actor 1”、“ Actor 2”、“ Actor 3”、“ Actor 4”、“ Actor 5”、“ Actor 6”]
边缘:
("凯文培根", "actor1", "movie1")
("凯文培根", "actor2", "movie1")
(" Actor 1", " Actor 2", "电影 1")
(" Actor 1", " Actor 3", "电影 2")
(" Actor 3", " Actor 2", "电影3")
(" Actor 3", " Actor 4", "电影4")
(" Actor 5", " Actor 6", "电影5")
其中 movie 是边名称或权重,元组的其他部分是顶点。我希望 BFS 算法打印出所有边和 kevin bacon 编号,或者打印出如果无法到达 Actor 则不可能。
这是到目前为止的代码。感谢您提供任何建议和帮助。
谢谢你的时间
class Vertex:
'''
keep track of the vertices to which it is connected, and the weight of each edge
'''
def __init__(self, key):
'''
'''
self.ID = key
self.connected_to = {}
def add_neighbor(self, neighbor, weight=0):
'''
add a connection from this vertex to anothe
'''
self.connected_to[neighbor] = weight
def __str__(self):
'''
returns all of the vertices in the adjacency list, as represented by the connectedTo instance variable
'''
return str(self.ID) + ' connected to: ' + str([x.ID for x in self.connected_to])
def get_connections(self):
'''
returns all of the connections for each of the keys
'''
return self.connected_to.keys()
def get_ID(self):
'''
returns the current key id
'''
return self.ID
def get_weight(self, neighbor):
'''
returns the weight of the edge from this vertex to the vertex passed as a parameter
'''
return self.connected_to[neighbor]
class Graph:
'''
contains a dictionary that maps vertex names to vertex objects.
'''
def __init__(self):
'''
'''
self.vert_list = {}
self.num_vertices = 0
def __str__(self):
'''
'''
edges = ""
for vert in self.vert_list.values():
for vert2 in vert.get_connections():
edges += "(%s, %s)\n" %(vert.get_ID(), vert2.get_ID())
return edges
def add_vertex(self, key):
'''
adding vertices to a graph
'''
self.num_vertices = self.num_vertices + 1
new_vertex = Vertex(key)
self.vert_list[key] = new_vertex
return new_vertex
def get_vertex(self, n):
'''
'''
if n in self.vert_list:
return self.vert_list[n]
else:
return None
def __contains__(self, n):
'''
in operator
'''
return n in self.vert_list
def add_edge(self, f, t, cost=0):
'''
connecting one vertex to another
'''
if f not in self.vert_list:
nv = self.add_vertex(f)
if t not in self.vert_list:
nv = self.add_vertex(t)
self.vert_list[f].add_neighbor(self.vert_list[t], cost)
def get_vertices(self):
'''
returns the names of all of the vertices in the graph
'''
return self.vert_list.keys()
def __iter__(self):
'''
for functionality
'''
return iter(self.vert_list.values())
def bfs(self):
'''
Needs to be implemented
'''
pass
最佳答案
您在这里遇到的最困难的问题是记录您已经访问过的顶点。因此,我认为您的算法应该检查顶点列表。一些假设:
好的,我们走。
def bfs(self, actor):
from heapq import heappush, heappop
if actor == "Kevin Bacon":
return print("This actor is Kevin Bacon!")
visited = set()
checked = []
n = 0
heappush(checked, (0, n, [self.get_vertex(actor)]))
# if the list is empty we haven't been able to find any path
while checked:
# note that we pop our current list out of the list of checked lists,
# if all of the children of this list have been visited it won't be
# added again
current_list = heappop(checked)[2]
current_vertex = current_list[-1]
if current_vertex.ID == "Kevin Bacon":
return print(current_list)
for child in current_vertex.get_connections():
if child in visited:
# we've already found a shorter path to this actor
# don't add this path into the list
continue
n += 1
# make a hash function for the vertexes, probably just
# the hash of the ID is enough, ptherwise the memory address
# is used and identical vertices can be visited multiple times
visited.add(child)
w = sum(current_list[i].get_weight(current_list[i+1])
for i in range(len(current_list)-1))
heappush(checked, (w, n, current_list + [child]))
print("no path found!")
您还应该为您的顶点类实现一个 __repr__() 方法。使用我使用的那个,输出如下所示:
g = Graph()
for t in [("Kevin Bacon", "actor1", "movie1")
,("Kevin Bacon", "actor2", "movie1")
,("actor1", "actor2", "movie1")
,("actor1", "actor3", "movie2")
,("actor3", "actor2", "movie3")
,("actor3", "actor4", "movie4")
,("actor5", "actor6", "movie5")]:
g.add_edge(t[0],t[1],cost=1)
g.add_edge(t[1],t[0],cost=1)
g.bfs("actor4")
# prints [Vertex(actor4), Vertex(actor3), Vertex(actor2), Vertex(Kevin Bacon)]
我原本不打算使用 heapq这样做,但最后决定我也可以。本质上,您需要对检查列表进行排序以首先获得最短路径。最简单的方法是每次要从顶部弹出最小值时对列表进行排序,但是当列表变大时,这会变得非常慢。 Heapq 可以保持列表以更高效的方式排序,但是没有关键方法来获取我们添加的列表的最小值,因此我们需要使用元组来伪造它。元组中的第一个值是路径的实际成本,而第二个值只是一个“决胜局”,这样我们就不会尝试比较顶点(它们没有排序,如果我们尝试这样做会引发异常).
关于python - Kevin Bacon 游戏的最短路径图遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47586428/
我正在学习使用神奇的 Bacon.js用于函数式响应式(Reactive)编程的库。向属性或流添加处理程序很容易: handler = function(value){... do something
我有以下 PHP 代码来生成 QR 码并显示到浏览器。 以下代码有效: $renderer = new \BaconQrCode\Renderer\Image\Png(); $
我有以下 PHP 代码来生成 QR 码并显示到浏览器。 以下代码有效: $renderer = new \BaconQrCode\Renderer\Image\Png(); $
在试验 Bacon.js 时,我遇到了以下意外行为: var email = $("#email") .asEventStream("k
my_Stream 是我想要累积并分配给变量以供进一步处理的数据。我的问题:一旦流完成,如何将变量 the_string 的内容获取到 console.log? my_Stream.onValue(f
我有一个定期触发的事件: let periodicEvent = Bacon.interval(1000, {}); periodicEvent.onValue(() => { doStuff
假设如下代码(当前状态可以查看 here ): function scrollTopFromEvent(evt) { return $(evt.target).scrollTop(); } f
我无法理解什么是 Bacon.js 中的惰性求值。 我使用 map 和 flatMap 编写了 Bacon 提供的示例,我得到了相同的结果。 这是HTML 这是使用 map 的代码的JS var
正如标题所说,我正在寻找一些组合器 collect,它将同时发出的事件收集到一个列表中,类似于 Reactive-Banana 中的那个。所以换句话说: collect :: EventStream
当按下 ENTER 时,我有一个事件流 var enter = $('#text') .asEventStream('keydown') .filter(function(e){
我想在 Bacon.js 中缓冲 EventStream 的值,就像 buffer(closingSelector) 一样在 RxJava 中表现。当“ Controller 流”(RxJava 方法
我有一个要向其发出 get 请求的 url 数组。我从 urls 数组和 flatMap ajax 请求创建一个流,如下所示:响应 = Bacon.fromArray(url_arr) .flatMa
我想在以下场景中使用 bacon.js: 1.读取目录下的文件 2.每个文件由一个url组成,向该url发起http请求 3.将每个响应写入另一个目录中的相应文件 从文档中,我了解到,即使所有值都被过
使用 Bacon.js 处理 POC 并遇到一些属性值问题。 我能够在 onValue 回调中检索所有新的属性值,但是我想知道设置此新值之前旧的属性值是什么。到目前为止,我还没有找到任何简单或优雅的解
我一直在尝试为流行的 kevin bacon 游戏创建图形表示。我已经创建了图形和顶点类,但在创建广度优先搜索方法来遍历图形并找到从 Kevin Bacon 到 Actor 的最短路径并在途中打印出边
我正在尝试为 requestAnimationFrame 生成类似于 Bacon.fromPoll 的流 为什么以下代码会产生“超出最大调用堆栈”错误? function rafSequence()
关于响应式编程的大部分资源,例如“A Survey on Reactive Programming”(Bainomugisha 等人,2012 年),介绍了几个可以对不同的响应式(Reactive)解
作为 bacon.js 的新手,我似乎无法理解事件流和属性之间的区别。 属性是从流构建的(使用 .constant 构建的属性除外?) 他们有大多数共同的方法 以同样的方式订阅它们 有人可以解释差异以
我有一个表单,当前有 2 个输入(数量将会增加),用户可以在其中添加/编辑数字。更改任何字段后,我想用这两个数字进行计算。 使用基本的 jQuery,这将是轻而易举的事情: var f1 = $(".
我正在尝试深入研究响应式编程。因此,我决定使用 Bacon javascript 库创建一个使用 RSA 加密的简单聊天。 我的问题:使用 Bacon 创建随机数流的最佳方法是什么?之后我想将随机数流
我是一名优秀的程序员,十分优秀!