I am trying to do Project Euler problem 8. Here is the general idea behind what I am doing:
I had several issues come up with my program and in my troubleshooting process I've found that, for some reason, my list that stores the current row is getting shortened until it is non-existent. I'm not sure why this is happening, what can I do to fix this?
Here is my source code:
with open("product.txt") as f:
array = []
for line in f:
line = line.split()
if line:
line = [int(i) for i in line]
array.append(line)
def product(k): #Largest product of row k
i = 0 #The start of the chunk of 13 terms
row = str(array[k][0])
while i < len(row) - 12: #Stop when i is 13 characters away from end of row
j=0 #The start of our run-through of the chunk
total = 1 #Set this value to 1 so that we can compare the next chunk of 13
while j < 13: #Go outward to the 12th element only since we include 0
total = total * int(row[i+j]) #The first character * the next 12
j += 1
#End of j while
print (row[i:13]) #To verify that the program is reading size 13 blocks
i += 1 #End of i while
return total
print (product(0))
The text file is just a copy and paste of the numbers from problem 8 .
Your list is not being shortened anywhere, you are simply printing a smaller and smaller slice.
You are using a fixed end-point for your slice:
print (row[i:13])
You want to make that end point relative to the start:
print(row[i:i + 13])
Euler problems are perfect for learning the basics of many computer languages, especially python. Euler 8 can be a single line code, like so:
print max([reduce(lambda x,y: x*y,map(int,input_string[i:i+13])) for i in xrange(len(input_string)-13)])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.