-1

I am faced with this strange error, and wasted 2 hours on it, but couldn't come up with explanation



    import math

    ipd={1:[2,3],2:[1],3:[1],4:[5,6,7],5:[4,6],6:[4,5],7:[4]}
    gkeys = [k for k in ipd.iterkeys()]
    key_map = {}

    for x in range(len(gkeys)):
        key_map[x] = gkeys[x]

    val = len(gkeys)
    #adj matrix...
    W = [[0.0]*val]*val
    print W
    for i in range(len(gkeys)):
        for j in range(len(gkeys)):
            #if i and j has edge...
            if key_map[j] in ipd[key_map[i]]:
                deg1 = len(ipd[key_map[j]])
                deg2 = len(ipd[key_map[i]])     
                v = 1.0/math.sqrt(deg1*deg2)
                W[i][j] = v
                print i,j,deg1,deg2,W[i][j], W[j][i]

Here is whole problem

For i=3 and j=5 first W[i][j] is 0.4248.. But for i=5, and j=3 W[j][i] is giving 0.5, how this is possible.

Thanks!

  • The issue you're having has to do with how you create `W`. It's items are all references to the same list, not several independent lists. – Blckknght Apr 19 '14 at 21:16

1 Answers1

0
W = [[0.0]*val]*val

The above gives you val copies of the exact same list. Try this:

a = [[0] * 4] * 4
print a
a[0][0] = 99
print a

Output:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
[[99, 0, 0, 0], [99, 0, 0, 0], [99, 0, 0, 0], [99, 0, 0, 0]]
ooga
  • 15,423
  • 2
  • 20
  • 21