2

Hello i'm trying to code the generation of an adjacency matrix from an edge list but i can't get my code to work and i don't understand why

i've tried inversing the indexes and running it step by step

graph1=[[0,2,3,4],[1,2,4],[0,2,3,4],[1,2,3,4],[0,2,4]]

def Adjacency(graph):
    index = 0  #Index of the sublist
    matrix = [[0]*len(graph)]*len(graph)
    print(matrix)  
    for sublist in graph:
        for value in sublist:
            print(value)
            matrice[index][value] = 1
        index+=1

    print(matrix)

Adjacence(graphe1) 

the expected output should be

[[1 0 1 1 1]
 [0 1 1 0 1]
 [1 0 1 1 1]
 [0 1 1 1 1]
 [1 0 1 0 1]] 

but instead i got

[[1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1]]

i'm pratically sure that i forgot a small detail but i can't figure it out. i'd be glad if somebody could me.

Slite
  • 159
  • 2
  • 2
  • 13

1 Answers1

3

you need to change the line:

matrix = [[0]*len(graph)]*len(graph)

to:

matrix = [[0]*len(graph) for i in range(len(graph))]

This is becasue when you make an array the way you did it stores them differently and they can edit multiple values at once. Try reading this question or this one

Buzz
  • 1,877
  • 21
  • 25