Why am I getting this error, from line 5 of my code, when attempting to solve Project Euler Problem 11?
for x in matrix:
p = 0
for y in x:
if p < 17:
currentProduct = int(y) * int(x[p + 1]) * int(x[p + 2]) * int(x[p + 3])
if currentProduct > highestProduct:
print(currentProduct)
highestProduct = currentProduct
else:
break
p += 1
'generator' object is not subscriptable
Your
x
value is is a generator object, which is anIterator
: it generates values in order, as they are requested by afor
loop or by callingnext(x)
.You are trying to access it as though it were a list or other
Sequence
type, which let you access arbitrary elements by index asx[p + 1]
.If you want to look up values from your generator's output by index, you may want to convert it to a list:
This solves your problem, and is suitable in most cases. However, this requires generating and saving all of the values at once, so it can fail if you're dealing with an extremely long or infinite list of values, or the values are extremely large.
If you just needed a single value from the generator, you could instead use
itertools.islice(x, p)
to discard the firstp
values, thennext(...)
to take the one you need. This eliminate the need to hold multiple items in memory or compute values beyond the one you're looking for.