Kibbee.ca
icon
Project Euler: Problem 8

Find the greatest product of five consecutive digits in the 1000-digit number.

[Full Question]

#open the file
data = open("Problem_00008data.txt")

digits = []

maxProduct = 0
#read in the first 5 characters
for i in range(0,5):
    digits.append(data.read(1))

#loop until we reach the end of the file
while True:
    product = 1
    #For all the characters in our array
    #Find the product
    for digit in digits:
        product = product * int(digit)
    
    #If this is the maximum product, then
    #set the new value
    if product > maxProduct:
        maxProduct = product
    
    #remove the first digit
    #and append another digit to the list
    digits.pop(0)
    digit = data.read(1)
    if digit == "":
        break
    else:
        digits.append(digit)
    
#close off the data file
data.close()

print "Maximum product is: %d" % (maxProduct,)

[Download Code]    [Download Data File]

A pretty straight forward question. I decided to put the data into a file so I could work on reading files in Python which is something I haven't done yet. I put the data into one big line so the data would be easier to deal with. I also choose to use a list to store the current list of digits I was checking. This was quite convenient because I could just keep popping digits off the list, and appending new digits to it.

No Comments Posted