有人提到下面的函数(在这种情况下是方法)不好,因为它在迭代列表时会修改列表。为什么会这样,因为它完全按照我的意图工作。我实际上对它很满意......有没有更好的写法。
数据结构、函数和输出如下:
nodes = { ('foo','bar',1),
('foo','baz',1),
('baz','gad',0),
('boo','moo',1),
('goo','loo',0),
('bar','far',1),
('far','aaa',0) }
class Graph(dict):
def __missing__(self, key):
self[key] = set()
return self[key]
def add_node_pairs(self, node_pairs):
for pair in node_pairs:
nodeA, nodeB, weight = pair
self[nodeA].add((weight, nodeB))
self[nodeB].add((weight, nodeA))
def find_paths(self, keys):
paths = [(key,) for key in keys if key in self]
for path in paths:
*oldkeys, key = path
for weight, next_key in self[key]:
if next_key not in oldkeys:
paths.append( path + (weight,next_key) )
paths.sort()
return paths
graph = Graph()
graph.add_node_pairs(nodes)
print(graph)
print( graph.find_paths(['foo']))
图形:
{ 'goo': {(0, 'loo')},
'foo': {(1, 'bar'), (1, 'baz')},
'aaa': {(0, 'far')},
'far': {(1, 'bar'), (0, 'aaa')},
'baz': {(0, 'gad'), (1, 'foo')},
'loo': {(0, 'goo')},
'moo': {(1, 'boo')},
'boo': {(1, 'moo')},
'bar': {(1, 'far'), (1, 'foo')},
'gad': {(0, 'baz')} }
find_paths ('foo'):
[ ('foo',),
('foo', 1, 'bar'),
('foo', 1, 'bar', 1, 'far'),
('foo', 1, 'bar', 1, 'far', 0, 'aaa'),
('foo', 1, 'baz'),
('foo', 1, 'baz', 0, 'gad') ]