Answer to Question #294800 in Python for eranna

Question #294800

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


1
Expert's answer
2022-02-07T12:50:35-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