1

有没有更好的方法来编写这个函数?

def highest_strength(G):
    highest_strength = None
    highest_strength_val = 1
    for node1 in G:
        for node2 in G[node1]:
            val = G[node1][node2]
            if val > highest_strength_val:
                highest_strength_val = val
                highest_strength = (node1, node2)
    return highest_strength
4

1 回答 1

4

非常简单:

def highest_strength(graph):
    return max((s, x, y) for x, links in graph.items() for y, s in links.items())

它是如何工作的:

>>> highest_strength(graph)
(4, 'c', 'b')

扩展版:

def highest_strength(G):
    best_strength, best_link = None, (None, None)
    for x, links in G.items():
        for y, v in links.items():
            if v > best_strength:
                best_strength, best_link = v, (x, y)
    return best_link
于 2012-12-20T12:19:20.140 回答