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)

Imports

import numpy

We’re using numpy (imported as numpy) because we want to handle 2D arrays in a more efficient and compact way.


The loadFile(fName) function

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
  1. Open the file:

    f = open(fName)
    
  2. Read N:

    N = int(f.readline())
    
  3. Read the spotlight coordinates:

    lCoords = []
    
    for line in f:
        x, y = line.split()
        lCoords.append((int(x), int(y)))
    
  4. Close the file:

    f.close()
    
  5. Return N and lCoords:


The main block

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:

  1. if __**name__** == “__main__”:

  2. Load the file:

    N, lC = loadFile("ex5_data.txt")
    
  3. Create an N x N numpy array of zeros:

    matrix = numpy.zeros((N, N))
    
  4. 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
    
    1. Outer 5 x 5 region:

      matrix[max(x - 2, 0):x + 3, max(y - 2, 0):y + 3] += 0.2
      
      • We want to add 0.2 to the region from (x - 2, y - 2) up to (x + 2, y + 2).
      • In Python slicing, 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.
      • We use 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.
      • Same logic for y on the second dimension.
    2. Middle 3 x 3 region:

      matrix[max(x - 1, 0):x + 2, max(y - 1, 0):y + 2] += 0.3
      
      • This covers (x - 1, y - 1) up to (x + 1, y + 1).
      • Adds 0.3 there. Again max(…) is used to prevent negative indexing out of bounds.
    3. Spotlight’s own tile:

      matrix[x, y] += 0.5
      
      • The tile where the spotlight actually sits gets an extra 0.5.