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 に答える