Sajad Rastegar
Sajad Rastegar

Reputation: 3154

A more pythonic way

Is there any better way to write this function?

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

Upvotes: 1

Views: 118

Answers (1)

defuz
defuz

Reputation: 27581

Very simple:

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

How it's work:

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

Expanded version:

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

Upvotes: 4

Related Questions