import numpy
def loadFile(fName):
f = open(fName)
N = int(f.readline())
lCoords = []
for line in f:
x, y = line.split()
lCoords.append((int(x), int(y)))
f.close()
return N, lCoords
if __name__ == "__main__":
N, lC = loadFile("ex5_data.txt")
matrix = numpy.zeros((N, N))
for x, y in lC:
matrix[max(x - 2, 0):x + 3, max(y - 2, 0):y + 3] += 0.2
matrix[max(x - 1, 0):x + 2, max(y - 1, 0):y + 2] += 0.3
matrix[x, y] += 0.5
print(matrix)
import numpy
We’re using numpy (imported as numpy
) because we want to handle 2D arrays in a more efficient and compact way.
def loadFile(fName):
f = open(fName)
N = int(f.readline())
lCoords = []
for line in f:
x, y = line.split()
lCoords.append((int(x), int(y)))
f.close()
return N, lCoords
Open the file:
f = open(fName)
fName
.Read N
:
N = int(f.readline())
N
(the size of the room, i.e., the dimension N x N
).Read the spotlight coordinates:
lCoords = []
for line in f:
x, y = line.split()
lCoords.append((int(x), int(y)))
x
and y
.x
and y
into integers, and store them in the list lCoords
as tuples (x, y)
.Close the file:
f.close()
Return N
and lCoords
:
if __name__ == "__main__":
N, lC = loadFile("ex5_data.txt")
matrix = numpy.zeros((N, N))
for x, y in lC:
matrix[max(x - 2, 0):x + 3, max(y - 2, 0):y + 3] += 0.2
matrix[max(x - 1, 0):x + 2, max(y - 1, 0):y + 2] += 0.3
matrix[x, y] += 0.5
print(matrix)
Let’s dissect it:
if __**name__** == “__main__”:
Load the file:
N, lC = loadFile("ex5_data.txt")
loadFile(…)
to get back:
N
: the dimension of the square room.lC
: a list of all the spotlight coordinates.Create an N x N
numpy array of zeros:
matrix = numpy.zeros((N, N))
Loop over each spotlight (x, y)
:
for x, y in lC:
matrix[max(x - 2, 0):x + 3, max(y - 2, 0):y + 3] += 0.2
matrix[max(x - 1, 0):x + 2, max(y - 1, 0):y + 2] += 0.3
matrix[x, y] += 0.5
(x, y)
.Outer 5 x 5 region:
matrix[max(x - 2, 0):x + 3, max(y - 2, 0):y + 3] += 0.2
0.2
to the region from (x - 2, y - 2)
up to (x + 2, y + 2)
.A[a:b]
goes up to but does not include b
, so going from x - 2
to x + 3
ends up covering indices x - 2, x - 1, x, x + 1, x + 2
.max(x - 2, 0)
to avoid going out of the matrix’s bounds. If x - 2
is negative, we use 0 as the start so we don’t slice outside the array.y
on the second dimension.Middle 3 x 3 region:
matrix[max(x - 1, 0):x + 2, max(y - 1, 0):y + 2] += 0.3
(x - 1, y - 1)
up to (x + 1, y + 1)
.0.3
there. Again max(…)
is used to prevent negative indexing out of bounds.Spotlight’s own tile:
matrix[x, y] += 0.5
0.5
.0.2
, an inner 3 x 3 area by an additional 0.3
and the exact tile by 0.5
. If you add those up, the center tile effectively gets 1.0
if it’s not overlapping with any other spotlight. But if multiple spotlights overlap, intensities accumulate.