Tuesday, May 29, 2018

Contrasting Styles - Inverting an Adjacency Graph

Mine :

def inverse_graph(graph):
    invG = []
    for i,row in enumerate(graph) :
        sieve = [1] * len( row )
        sieve[i] = 0
        invG.append( [xor(x[0], x[1]) for x in zip(row, sieve)] )
    return invG

Instructor :

def inverse_graph(graph):
    n = len( graph )
    invG = []
    for i in range( n ) :
        invG.append( [] )
        for j in range( n ) :
             if i != j :
                   invG[i].append( 1 - graph[i][j] )
             else :
                   invG[i].append( 0 )
    return invG

Which do you feel is more idiomatic?

Here's a handy hack - if you had a list of ints, which is a subset of the first n non-negative ints (0,1,2,.. n-1), how do you build yourself a list of ones and zeros such that the entry is a one when the ordinal number representing that entry is in the list of ints? ( [0,1,4], 5 ) --> [ 1, 1, 0 , 0 , 1] )

sieve = list(map(lambda x: 1 if x in cover else 0, range(len(graph))))

Like?

No comments: