Project Euler Problem 8. Code doesn't work. Unsure why


I need to iterate through a long number to find the 13 consecutive digits with the greatest product. My code to do this looks like:

def largest_product(long_number, running_total, total): 
    long_number = str(long_number) 
	count = -1
	for digit in long_number:
		count += 1
		if len(long_number[count:count+13]) == 13:
			for digi in long_number[count:count+13]:
				running_total *= int(digi)
		if running_total > total:
				total = running_total
	print total

However this results in running total being set to 0 after the first total is calculated, in spite of giving it a value of 1 when calling it. Sorry about lack of indentation. I'm new to posting on the forums and unsure how to use tabs.


Hi @scriptrockstar72264 ,

EDIT: This topic should probably go in the Corner Bar category.

Add a statement outside the function that sets a variable, num, to string that contains all the digits in the number that needs to be processed, for example ...

num = "67432984501827743972459398172"

... but, obviously, a longer number.

The largest_product function only needs to take one parameter, which would be used to pass it the string that represents that long number.

Inside the function, first do this ...

greatest_product = 0

You have variables named total and running_total, but the problem is really about computing products, not totals.

Then inside your loop, update the value of greatest_product each time you find a product that exceeds the current value of that variable.

Finally, after the loop, return the greatest_product.

Try this out, after the first statement that assigns to num a string representing the digits in the long number ...

def largest_product(long_number):
    greatest_product = 0
    count = -1
    for digit in long_number:
        running_product = 1
        count += 1
        if len(long_number[count:count+13]) == 13:
            for digi in long_number[count:count+13]:
                running_product *= int(digi)
            if running_product > greatest_product:
                greatest_product = running_product
    return greatest_product

print largest_product(num)