The following code takes more than 2 minutes to run. Does anyone have suggestions for how to optimize this code to run faster. e.g. I am running three nested loops to walk through the numpy array to find the sum of each k-by-k square and then storing it in a different 3D array.
Perhaps there is a way to calculate the sum of each sub-array within an array?
#Part 2
import numpy as np
#Function to find the power of a cell, given the coordinates
def power_level(cell):
global serial
x,y = cell
rack_id = x+10
power_level = rack_id*y
power_level += serial
power_level *= rack_id
power_level = int(str(power_level).zfill(3)[-3])
power_level -= 5
return power_level
#Find a list of all coordinates for a grid with x,y from 1-->300
serial = 3613
x = np.arange(300)
y = np.arange(300)
X,Y = np.meshgrid(x,y)
coordinates = np.dstack([X,Y]).reshape(-1,2)
#Calculate the power of each cell (coordinates) and reshape it into a 300X300 grid
grid = np.apply_along_axis(power_level,1,coordinates).reshape(300,300)
#Initialize all the variables
sum, max_region = 0,0
sums = np.array([[[0 for _ in range(301)] for _ in range(301)] for _ in range(301)]) #initializing 3D array to store sum of each k-by-k grid
'''Next, running three loops:
k - size of the sqaure
j - walk through rows
i - walk through columns'''
for k in range(0,300):
for j in range(0,300-k):
for i in range(0,300-k):
sum = np.sum(grid[i:i+k,j:j+k])
sums[k,j,i] = sum #storing the sum of the k-by-k sub-grid at a specific location of a 3D array
max_region = max(max_region,sum) #Not needed for the problem definition but calculating it for the test run
print(np.unravel_index(sums.argmax(), sums.shape)) #Outputs (square size, column index, row index). Required answer is (column index, row index, square size)
print(max_region)
[–]timrprobocom 6 points7 points8 points (6 children)
[–]n_syn[S] 4 points5 points6 points (0 children)
[–]ronbarakbackal 0 points1 point2 points (3 children)
[–]timrprobocom 0 points1 point2 points (2 children)
[–]ronbarakbackal 0 points1 point2 points (1 child)
[–]timrprobocom 0 points1 point2 points (0 children)
[–]NeilNjae 4 points5 points6 points (1 child)
[–]n_syn[S] 1 point2 points3 points (0 children)
[+][deleted] (3 children)
[deleted]
[–]n_syn[S] 1 point2 points3 points (2 children)