-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm2.py
More file actions
47 lines (35 loc) · 1.73 KB
/
algorithm2.py
File metadata and controls
47 lines (35 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def createMatrix(m): #function to initialize matrix with -999
matrix = []
for i in range(m):
row = []
for j in range(m):
row.append(-999)
matrix.append(row)
return matrix
def printMatrix(matrix): #function to print adjacency matrix
print("Adjacency Matrix\n")
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(f"{matrix[i][j]:5}", end=" ") #for formatting
print("\n")
def solveProblem(file):
with open(file, "r") as inputFile:
vertices = inputFile.readline().strip() #get rid of newline
vertices = vertices.split(" ") #split array by space
my_dict = {}
for i, v in enumerate(vertices): #get index and item from vertices array
my_dict[v] = i #assign values to corresponding indices for matrix position
m = len(vertices)
matrix = createMatrix(m)
for line in inputFile:
line = line.strip().replace(" ", "") #get tid of empty space
line = line.split(",") #split by commas to create array and delete newline
first = line[0] #first letter
second = line[1] #second letter
distance = int(line[2]) #convert distance from str to int
i, j = my_dict[first], my_dict[second] #i represents index of first letter
#j represents index of second letter to determine position in matrix
matrix[i][j] = distance #assign specific position in matrix to distance between the two letters
printMatrix(matrix) #print the adjacency matrix
inputFile.close() #close file to avoid issues
solveProblem("input.txt")