Answer to Question #294953 in Python for Sathvika Pallapothula

Question #294953

 Given an input undirected graph, create and print the adjacency list and adjacency matrix representations of the graph. Input Format: The input is a text file which describes an undirected graph. The first line of the file specifies n & m, the number of vertices and number of edges in the graph respectively. The next m lines specify the m edges of the graph, one line per edge. An edge is described by its end points. If the number of vertices is n, assume that the vertices of the graph are numbered (0,1,..n-1). Output Format: Print the adjacency list and adjacency matrix representation of the graph. In the adjacency list representation, for a given vertex, the order of its adjacent vertices does not matter.


1
Expert's answer
2022-02-08T01:16:03-0500
# There is no need to specify the number of vertices and edges in the file as
# this is redundant information. For this reason, the script uses a file that
# contains only the matrix without any other information.
import numpy as np

def read_f(name_f):
    given_file = open(name_f, 'r')

    lines = given_file.readlines()
    digits = []
    for line in lines:
        for c in line:
            if c.isdigit() == True:
                digits.append(int(c))
    given_file.close()
    size_g = int(len(digits)**(1/2))
    digits = np.array(digits).reshape(size_g, size_g)
    for i in range(size_g):
        for j in range(size_g):
            if i == j:
                digits[i][j] = 0
            elif digits[i][j] > 0:
                digits[i][j] = 1
                digits[j][i] = 1
    print("Result matrix: \n", digits)
    print('The adjacency list representation: ')
    for i in range(size_g):
        row = []
        for j in range(size_g):
            if digits[i][j] == 1:
                row.append(j)
        print(f'{i}: ', row)


def main():
    name_f = 'test.txt'
    read_f(name_f)

if __name__ == "__main__":
    main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS