Reputation: 67
enter code here
def prims():
r = 4;
c = 4;
total = 0
matrix = [ [0 for x in range(r)] for y in range(c)]
min = 999
u = 0
v = 0
visited = [None]*4
for i in range(0,4):
visited[i] = 0
for j in range(0,4):
matrix[i][j] = input()
if matrix[i][j]== 0:
matrix[i][j] = 999
visited[0] = 1
for counter in range(0,3):
min = 999
for i in range(0,4):
if visited[i] == 1:
for j in range(0,4):
if visited[j] != 1:
if min > matrix[i][j]:
min = matrix[i][j]
a = u = i
b = v = j
visited[v] = 1
total = total + min
print("edge found :{}->{}:{}".format(u,v,min))
print("The weight of minimum spanning tree is : {}".format(total))
return
prims()
What I have to do, if I want go give input as text file to this program. I have created a file named "input.txt".There I put inputs of matrix. Can anyone help me with solution please.
input.txt :
0 28 999 999 999 10 999
28 0 16 999 999 999 14
999 16 0 12 999 999 999
999 999 12 0 22 999 18
999 999 999 22 0 25 24
10 999 999 999 25 0 999
999 14 999 18 24 999 999
Upvotes: 1
Views: 74
Reputation: 284
Here is the way to read from file
file = open('path of input file')
for line in file.readlines():
print(list(map(int, line.split(' '))))
file.close()
you can store it to an array as well by doing
arr = []
file = open('path of input file')
for line in file.readlines():
arr.append(list(map(int, line.split(' '))))
print(arr)
file.close()
output is
[[0, 28, 999, 999, 999, 10, 999], [28, 0, 16, 999, 999, 999, 14], [999, 16, 0, 12, 999, 999, 999], [999, 999, 12, 0, 22, 999, 18], [999, 999, 999, 22, 0, 25, 24], [10, 999, 999, 999, 25, 0, 999], [999, 14, 999, 18, 24, 999, 999]]
Upvotes: 2
Reputation: 710
If I understand correctly, you are looking for a way to transform input such as:
0 28 999 999 999 10 999
28 0 16 999 999 999 14
999 16 0 12 999 999 999
999 999 12 0 22 999 18
999 999 999 22 0 25 24
10 999 999 999 25 0 999
999 14 999 18 24 999 999
Which you get from file, into matrix ixj
.
matrix = []
with open('test.txt') as file:
for line in file:
matrix.append([int(val) for val in line.split()])
You get result:
matrix
Out[93]:
[[0, 28, 999, 999, 999, 10, 999],
[28, 0, 16, 999, 999, 999, 14],
[999, 16, 0, 12, 999, 999, 999],
[999, 999, 12, 0, 22, 999, 18],
[999, 999, 999, 22, 0, 25, 24],
[10, 999, 999, 999, 25, 0, 999],
[999, 14, 999, 18, 24, 999, 999]]
And of course you can use indexing:
matrix[1][2]
Out[94]: 16
Upvotes: 1