I have this code, which splits a number into groups of 5, puts them into a list, and then multiples them. This is Problem 8 in Project Euler, if you're confused. It's also not finished, as I need to find the other possible 5 consecutive integers.
def split_number(number, n):
line = str(number)
split = [line[i:i+n] for i in range(0, len(line), n)]
return split
splitnum = split_number((extremely long number), 5)
for x in enumerate(splitnum[:-1]):
split5 = split_number(splitnum[x], 1)
for n in split5:
splitproduct = reduce(lambda x, y: x*y, splitnum[n])
if (splitproduct > solution):
solution = splitproduct
print solution
When I try to run this, I get the error
TypeError: list indices must be integers, not tuple
I guess when I iterate through splitnum, x is a tuple. I need it to be an integer so I can use split5() correctly.
New code:
def split_number(number, n):
line = str(number)
split = [line[i:i+n] for i in range(1, len(line)-n+1, n)]
return split
number =
while len(split_number(number,1)) is not 0:
splitnum = split_number((number), 5)
solution = 0
for x in splitnum[:-1]:
split5 = split_number(x, 1)
for n in split5:
splitproduct = reduce(lambda x, y: x*y, n)
if (splitproduct > solution):
solution = splitproduct
number = split_number(number, 1)
del number[0]
print solution
Now I'm getting a memory error on the 'split' line in function split_number. that's probably because of the extremely long number. But that isn't the topics question, I just wanted you guys to see how I implemented their solutions (which worked, because the program actually runs). :)
split_number([1, 2, 3, 4], 2)should yield1, 2,2, 3and3, 4, not1, 2and3, 4.rangeinsidesplit_numberback to1. Also you will want to setlen(line)-n+1as the maximum number so you don’t end up with four groups containing less than five numbers.split-list (i.e. don’t calculate more), then you should be fine.