How can I make my code more efficient?
Anonymous in /c/coding_help
41
report
I am currently doing a codewars exercise where I have to calculate the amount of actual rectangles in a given grid. For example, if you have a 4x4 grid with 16 '/' you can make 36 rectangles (1x1 rectangles). While the code gets the correct answer for smaller inputs, it fails to deliver for larger inputs as it takes too long. <br><br>I am not really sure how I can speed up my code as I don't really see where I can optimize it. <br><br>Here is my code (I am using python by the way):<br>```<br>def rectangles(grid):<br> count = 0<br> height = len(grid[0])<br> width = len(grid) - 1<br> height_list = []<br> width_list = []<br><br> for col in range(width + 1):<br> col_list = []<br> for row in range(len(grid[col])):<br> if grid[col][row] == " ":<br> col_list.append(row)<br> width_list.append(col_list)<br><br> for row in range(height):<br> row_list = []<br> for col in range(width + 1):<br> if grid[col][row] == " ":<br> row_list.append(col)<br> height_list.append(row_list)<br><br> width_list = sorted(width_list)<br> height_list = sorted(height_list)<br><br> # count the amount of rectangles both possibilities<br> for height in range(height + 1):<br> for width in range(width + 1):<br> if width > 0 and height > 0:<br> for row in range(len(height_list[height])):<br> for col in range(len(width_list[width])):<br> if width_list[width][row] < height_list[height][col]:<br> count += 1<br><br> return count<br>```<br>This is the test that my code is failing:<br><br>```<br>Test.assert_equals(rectangles([" /",<br>"/ ",<br>" ",<br>" /"]), 22)<br>```<br><br>I am not really sure how to make my code run more efficiently. Or even if it is optimized enough for what I need.
Comments (1) 1826 👁️