目前我正在创建一个名为randomwalk
的函数,它将集合edges
、传送概率a
和正整数iters
作为输入,并执行随机游走。你知道吗
从任何一个页面开始,函数将随机跟随从一个页面到下一个页面的链接,在每次迭代时以概率a
传送到一个完全随机的页面。你知道吗
它还应该存储所有访问的状态,并最终创建一个访问每个页面的频率直方图。这个直方图就是randomwalk函数将返回的结果
这是我到目前为止,我得到了一个不可修复的类型错误,虽然列表。这是边的列表
edges =[[0,1], [1,1], [2,0], [2,2], [2,3], [3,3], [3,4], [4,6], [5,5], [6,6], [6,3]]
def randomWalk(edges, a ,iters):
pages = {edge[0] for edge in edges}
dict_edges = {}
for edge_from, edge_to in edges:
if edge_from not in dict_edges:
dict_edges[edge_from] = [edge_to]
else:
dict_edges[edge_from].append(edge_to)
current_page = random.choice(pages)
visit_counts_dictionary = {page:0 for page in pages}
visit_counts_dictionary[current_page] +=1
for _ in range(iters):
if random.uniform(0,1) < a:
current_page = random.choice(pages)
visit_counts_dictionary[current_page] += 1
else:
current_page = random.choice(dict_edges[current_page])
visit_counts_dictionary[current_page] += 1
print visit_counts_dictionary
print(randomWalk(edges, 0, 10))
我该怎么解决这个问题?你知道吗
出现此错误的原因是在python中不能将
list
用作dict
中的键。改用tuple
:代码中的错误来自以下行:
您可能在
edges[0]
中出错,请将其更改为edge[0]
:相关问题 更多 >
编程相关推荐