I wrote the following function in Python3 for finding the largest product of numbers along the diagonal(top-left to right-bottom).
def GreatestOnDiagonal(data):
'''Returns greatest product possible by multiplying 4 numbers in the diagonal
'''
grtProduct=1
for item in data:
for n in item:
product=1
for r in range(0,4):
try:
d=data.index(item)+r
e=item.index(n)+r
product*=data[d][e]
except IndexError:
break
#
if product>grtProduct:grtProduct=product
return grtProduct
The parameter passed here,data, is a list of numbers from the grid in http://projecteuler.net/index.php?section=problems&id=11 . Each line is a list nested into the main list, data.
What I've tried to do here is-
Take 08 ,for example, which lies first on the grid. The position of 08 is 0 in the 0th list of the 'data' list. So the number along the diagonal would be the term 1 of the 1st list of the data list. Then the third number would be on the position 2 of the 2nd......... and so on. Right?
This seems to work fine for the numbers at the beginning, but at the end what the function has basically done is generate the row, which obviously would result in an error. Can someone guide me through this?? Thanks.