Reputation: 5200
Here's the code, part of a solution to problem 11 in Euler Project:
sum_d = 0
j = 0
while j < 20:
i = 0
while i < 20:
try:
sum_d = grid[j][i] * grid[j+1][i+1] * grid[j+2][i+2] * grid[j+3][i+3]
if sum_d > result:
result = sum_d
except IndexError:
pass
i += 1
j += 1
My question is whether catching those exceptions is considered a code smell? I can see that it will be tougher to debug such code (say, I accidentally looped over 19 items instead of 20, it will be harder to trace) but it is much more elegant then, say, coding i < (GRID_WIDTH - NUM_ITEMS_IN_PRODUCT)
in the loop check.
P.S. I already solved the problem, I'm talking about the style of code
Upvotes: 0
Views: 178
Reputation: 6919
You could at least make it
except IndexError:
break
Anyway, yes I believe this is a code smell, and no it is not clearer than
for i in range(gridsize - num_items_in_product):
Upvotes: 1
Reputation: 15537
Spoiler: Here's part of my solution for problem 11.
for x in range(0,16):
for y in range(0,16):
prod = p[y][x] * p[y+1][x+1] * p[y+2][x+2] * p[y+3][x+3]
m = max(m, prod)
Using exceptions instead of basic control structures is imho always a bad idea. This time you can get away with looping through the numbers 0..15!
Also, if you muliply stuff you get a product, not a sum. ;)
Upvotes: 7