0

I was wondering if I can get some help to print the adjacency matrix in python. The output that I am hoping to get is like below:

![enter image description here

Code is below:

import numpy

adjlist = [
          (1,2,15),
          (1,4,7),
          (1,5,10),
          (2,3,9),
          (2,4,11),
          (2,6,9),
          (3,5,12),
          (3,6,7),
          (4,5,8),
          (4,6,14),
          (5,6,8)
         ]


def matfn(adjlist, nodes):
    '''Returns a (weighted) adjacency matrix as a NumPy array.'''
    matrix = []

    for node in nodes:
        weights = {endnode:int(weight)
                   for w in adjlist.get(node, {})
                   for endnode, weight in w.items()}
        matrix.append([weights.get(endnode, 0) for endnode in nodes])
        matrix = numpy.array(matrix)
        return matrix + matrix.transpose()

matfn(adjlist, nodes=list('123456'))

(Pretty new to python...) Thanks in advance...

ESLearner
  • 87
  • 1
  • 14
  • See no error - postet as _text_ in your Q Edit it.. Please go over [how to ask](https://stackoverflow.com/help/how-to-ask) and [on-topic](https://stackoverflow.com/help/on-topic) again and if you have questions provide your code as [mvce](https://stackoverflow.com/help/mcve). If you encounter errors, copy and paste the error message verbatim ( word for word) into your question. Avoid using screenshots unless you need to convey layout errors. We can NOT copy and paste your image into our IDEs to fix your code. – Patrick Artner Mar 02 '18 at 20:09
  • Thats a good start - even better is to _also_ provide the error message. They are not cryptic if you know where to look and I do not need to copy /paste anything in my IDE if I know from the error desc whats wrong. By providing code and messge you make it easier to help you. - I copy & pasted non the less - the error is somewhere in `adjlist.get(node, {})` - you are trying to use a dict-method on a list. maybe make it a dict or use a np-array instead of a plain python list of tuples? My numpy-foo is not existent, so add numpy as tag as well and hope one of the cracks takes a look. – Patrick Artner Mar 02 '18 at 20:21
  • i think you'r method `matfn` comes from this [link](https://stackoverflow.com/questions/29464252/adjacency-matrix-in-python) question. there they answered for a graph represented by dictionary . so thats why here `adjlist.get(node, {})` gives you errors because here `adjlist` is a list – Sunimal S.K Malkakulage Mar 02 '18 at 20:36
  • My intent is for the function matfn to read the array of edges and convert to adjacency matrix and output the adjacency matrix or list with weights. @Sunimal - You are right , I did reference parts of the code from the link . Patrick - Will ensure I will format the question so its easier and of course will include the error :) – ESLearner Mar 02 '18 at 21:02

0 Answers0