1

For a given list of tuples L whose elements are taken from range(n), I want to create A binary matrix A of order n in the following way:

If (i,j)  or (j,i) in L then A[i][j]=1 otherwise A[i][j]=0.    

Let us consider the following example:

L=[(2,3),(0,1),(1,3),(2,0),(0,3)]
A=[[0]*4]*4
for i in range(4):
    for j in range(4):
        if (i,j) or (j,i) in L:
            A[i][j]=1
        else:
            A[i][j]=0

print A

This program does not give the accurate result. Where is the logical mistake occurred?

jpp
  • 159,742
  • 34
  • 281
  • 339
Primo Raj
  • 109
  • 1
  • 7
  • What do you mean under "does not give the accurate result"? – zwer Apr 24 '18 at 11:33
  • Possible duplicate of [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Aran-Fey Apr 24 '18 at 11:37
  • https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – Aran-Fey Apr 24 '18 at 11:37
  • 1
    Change `A=[[0]*4]*4` to `A=[[0]*4 for _ in range(4)]` and `(i,j) or (j,i) in L` to `(i,j) in L or (j,i) in L`. – Aran-Fey Apr 24 '18 at 11:39
  • I mean the out put should A=[[0,1,1,1,1],[1,0,0,1],[1,0,0,1],[1,1,1,0]] @zwer – Primo Raj Apr 24 '18 at 11:41
  • @Aran-Fey Thank you for your correction. Now this gives the desired result. – Primo Raj Apr 24 '18 at 11:45
  • @Aran-Fey Can you explain please. When I use A=[[0]*4]*4, the outcome gives wrong but when I use A=[[0]*4 for _ in range(4)], the outcome is correct, Why? – Primo Raj Apr 24 '18 at 11:47
  • It's already explained [here](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly). – Aran-Fey Apr 24 '18 at 11:48

2 Answers2

1

You should use a 3rd party library, numpy, for matrix calculations.

Python lists of lists are inefficient for numeric arrays.

import numpy as np

L = [(2,3),(0,1),(1,3),(2,0),(0,3)]

A = np.zeros((4, 4))

idx = np.r_[L].T
A[idx[0], idx[1]] = 1

Result:

array([[ 0.,  1.,  0.,  1.],
       [ 0.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.]])

Related: Why NumPy instead of Python lists?

jpp
  • 159,742
  • 34
  • 281
  • 339
0

According to Aran-Fey's correction the answer is :

L=[(2,3),(0,1),(1,3),(2,0),(0,3)]
#A=[[0]*4]*4
A=[[0]*4 for _ in range(4)]
for i in range(4):
    for j in range(4):
        if (i,j) in L or (j,i) in L:
            A[i][j]=1
        else:
            A[i][j]=0

print A
Primo Raj
  • 109
  • 1
  • 7