- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下代码可以实现拓扑顺序:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
self.V = 0 #number of nodes
def addEdge(self,u,v):
self.graph[u].append(v)
self.V = self.V + 1
def topologicalSortUtil(self,v,visited,stack):
visited[v] = True
for i in self.graph[v]:
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
stack.insert(0,v)
# topologicalSortUtil()
def topologicalSort(self):
# Mark all the vertices as not visited
visited = [False]*self.V
stack =[]
for i in range(self.V):
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
print stack
g= Graph()
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
g.topologicalSort()
它给出:
[5, 4, 3, 2, 1, 0]
现在,我希望我的代码能够处理字符串作为键:
g.addEdge('f', 'c')
g.addEdge('f', 'a')
g.addEdge('e', 'a')
g.addEdge('e', 'b')
g.addEdge('c', 'd')
g.addEdge('d', 'b')
(只需将数字更改为字母...0='a',1='b'等..)然而这不起作用。
它应该给出:
['f', 'e', 'd', 'c', 'b', 'a']
问题出在这里:
for i in range(self.V):
if visited[i] is False:
self.topologicalSortUtil(i, visited, stack)
代码在范围
上迭代,而不是在实际的节点键上迭代。
我尝试将其转换为:
for i in self.graph.items():
但它不起作用。
TypeError: list indices must be integers or slices, not tuple
我该如何解决这个问题?
最佳答案
有一些东西可以在您的Graph
类中进行概括,以接受字母和数字作为顶点的名称。
这里有一个建议:
class Graph:
def __init__(self, name_of_vertices):
self.graph = collections.defaultdict(list)
self.name_of_vertices = name_of_vertices # define all vertices by name
def add_edge(self, v, other_v):
self.graph[v].append(other_v)
def _topological_sort(self, v, visited, stack):
visited[v] = True
for other_v in self.graph[v]:
if not visited[other_v]:
self._topological_sort(other_v, visited, stack)
stack.insert(0, v)
def topological_sort(self):
# Mark all the vertices as not visited
visited = {
v: False
for v in self.name_of_vertices}
stack = []
for v in self.name_of_vertices:
if not visited[v]:
self._topological_sort(v, visited, stack)
print(stack)
然后你可以使用这个:
g = Graph(['z', 'a', 'b', 'c', 'd', 'e'])
g.add_edge('e', 'b')
g.add_edge('e', 'z')
g.add_edge('d', 'z')
g.add_edge('d', 'a')
g.add_edge('b', 'c')
g.add_edge('c', 'a')
g.topological_sort()
# prints: ['e', 'd', 'b', 'c', 'a', 'z']
g = Graph(list(range(6)))
g.add_edge(5, 2)
g.add_edge(5, 0)
g.add_edge(4, 0)
g.add_edge(4, 1)
g.add_edge(2, 3)
g.add_edge(3, 1)
g.topological_sort()
# prints: [5, 4, 2, 3, 1, 0]
关于python - 如何迭代defaultdict?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55524645/
从文件中读取并清理的文本: ['the', 'cat', 'chased', 'the', 'dog', 'fled'] 挑战是返回一个字典,其中每个单词作为值,可以跟随它的单词作为键,并计算它跟随它
使用 this answer ,我创建了 defaultdict 的 defaultdict。现在,我想把那个嵌套很深的 dict 对象变回一个普通的 python dict。 from collec
我的应用程序说参数必须是可调用的或无类型有什么特别的原因吗?我很确定这就是您使用 defaultdict 作为其值实例化 defaultdict 的方式。 dict = defaultdict(def
我想实现一个类似 dict 的数据结构,它具有以下属性: from collections import UserDict class TestDict(UserDict): pass tes
我有两个 defaultdict : defaultdict(, {'a': ['OS', 'sys', 'procs'], 'b': ['OS', 'sys']}) defaultdict(, {'
我有一个defaultdict(Set): from sets import Set from collections import defaultdict values = defaultdict(
我正在使用 defaultdict 来存储数百万个短语,所以我的数据结构看起来像 mydict['string'] = set(['other', 'strings'])。它似乎适用于较小的集合,但当
所以 defaultdict documentation提到,如果缺少某个项目,则 default_factory 返回的值“将插入字典中作为键,然后返回。”这在大多数情况下都很棒,但在这种情况下我真
我有一个默认的列表列表,但我基本上想这样做: myDefaultDict = filter(lambda k: len(k)>1, myDefaultDict) 除了它似乎只适用于列表。我能做什么?
这可能是一个愚蠢的问题,但是:我的代码运行良好,直到我尝试添加 ml.我尝试了几种方式但是 init_dict = [] with open("example.csv", "r") as new_da
我正在尝试将列表递归地转换为嵌套字典,如下所示:- 给定输入:- parse_list = ['A','B','C','D'] 所需输出:- data = [ {'name': 'A',
我有一个名为“n”的字典,其中有一个键值关系(字典中的字典)。 此处的 key 将是tenant_id (b77865b66fd544e0841aa7dbca8bdc97, 7b73b9644e824
我有一个 Excel 数据集列表,其中包含以下某些信息: Category Subcategory Name Main Dish Noodle Tomato Noodl
我有以下内容: a = [{ "_id" : { "reportId" : "5a27cda63fff647c33a14b31" }, "amount" : 3000 }, { "_id"
这很简单: 'foo {bar}'.format(**{'bar': 0}) 这不起作用,产生一个 KeyError: from collections import defaultdict d =
我有这个: dict1 = defaultdict(lambda:defaultdict(list)) dict1['rl1']['sh1'] = ['a','b'] dict1['rl1']['sh
我正在尝试在 python 中使用 defalultdict 和不赋值的行为 数据如下: data = {'APPLaunch_ftrace': [63.3, 24.5, 8.4, 2.3, 0.9,
我有一个字典列表。我们称它为:list_of_dict。列表中的词典采用以下形式: {'a' : 1, 'b' : 5, 'c' : 3, 'd' : 6} 和 {'a' : 3, 'f' : 2,
我想使用关键字解包运算符 ** 格式化和打印字典中的数据。 格式字符串可能引用了很多关键字,而字典可能没有所有需要的关键字。对于缺少的键,我想使用字符串“N/A”作为默认值。 我想要一个聪明的解决方案
考虑以下默认字典: data = defaultdict(list) data['key1'] = [{'check': '', 'sth1_1':'k1', 'sth1_2':'k2'}] data
我是一名优秀的程序员,十分优秀!