Skip to content

Commit 26f9491

Browse files
authored
update context manager (#302)
Co-authored-by: Humphrey Yang <humphrey.yang@anu.edu.au>
1 parent a897549 commit 26f9491

File tree

2 files changed

+13
-16
lines changed

2 files changed

+13
-16
lines changed

lectures/finite_markov.md

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1278,9 +1278,8 @@ n = 14 # Total number of web pages (nodes)
12781278
# * Q[i, j] = 1 if there is a link from i to j
12791279
# * Q[i, j] = 0 otherwise
12801280
Q = np.zeros((n, n), dtype=int)
1281-
f = open(infile, 'r')
1282-
edges = f.readlines()
1283-
f.close()
1281+
with open(infile) as f:
1282+
edges = f.readlines()
12841283
for edge in edges:
12851284
from_node, to_node = re.findall('\w', edge)
12861285
i, j = alphabet.index(from_node), alphabet.index(to_node)

lectures/short_path.md

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -399,19 +399,17 @@ def map_graph_to_distance_matrix(in_file):
399399
Q = np.full((num_nodes, num_nodes), np.inf)
400400
401401
# Now we read in the data and modify Q
402-
infile = open(in_file)
403-
for line in infile:
404-
elements = line.split(',')
405-
node = elements.pop(0)
406-
node = int(node[4:]) # convert node description to integer
407-
if node != destination_node:
408-
for element in elements:
409-
destination, cost = element.split()
410-
destination = int(destination[4:])
411-
Q[node, destination] = float(cost)
412-
Q[destination_node, destination_node] = 0
413-
414-
infile.close()
402+
with open(in_file) as infile:
403+
for line in infile:
404+
elements = line.split(',')
405+
node = elements.pop(0)
406+
node = int(node[4:]) # convert node description to integer
407+
if node != destination_node:
408+
for element in elements:
409+
destination, cost = element.split()
410+
destination = int(destination[4:])
411+
Q[node, destination] = float(cost)
412+
Q[destination_node, destination_node] = 0
415413
return Q
416414
```
417415

0 commit comments

Comments
 (0)