[英]Code for project euler number 67 getting wrong answer
我正在尝试解决 Project Euler 编号 67,而我的用于问题 18 的代码将无法正常工作,我最终得到了比预期 (7273) 更大的 (7320) 答案。
我不知道出了什么问题,以及我应该更改我的代码以修复它。
numbers =[
[59],
#...
]
sums = [
[59],
#...
]
#Adding the first two lines as I couldnt get them to work within the
#main algorithm
i = 0
x = 1
for y in range(0, len(numbers[x])):
for a in range(0, len(numbers[x - 1])):
temp1 = numbers[i][a] + numbers[x][y]
sums[x].append(temp1)
print(sums)
#The code basically just splits the trianglet into smaller triangles
#and adds them up going through the whole line
for x in range(1, len(sums) - 1):
#The bad array is used to store the sums which are smaller when two
#triangles overlap
bad = []
#Calculates the sums of the small triangles and puts them into a 2d
#array of the same size as the one which has all the numbers
for y in range(0, len(sums[x])):
temp1 = sums[x][y] + numbers[x + 1][y]
sums[x + 1].append(temp1)
temp1 = sums[x][y] + numbers[x + 1][y + 1]
sums[x + 1].append(temp1)
#This is where the 'bad' array comes into play, it checks overlapping
#triangles and takes out the smaller sum
for i in range(1, len(sums[x + 1]) - 2, 2):
if sums[x + 1][i] >= sums[x + 1][i + 1]:
a = sums[x + 1][i + 1]
bad.append(a)
if sums[x + 1][i + 1] > sums[x + 1][i]:
a = sums[x + 1][i]
bad.append(a)
#Here it removes all the 'bad' sums from the final array
for y in range(0, len(bad)):
for z in range(0, len(sums[x + 1]) - 1):
if sums[x + 1][z] == bad[y]:
sums[x + 1].pop(z)
break
#Here it print the maximum possible sum once it has reached the bottom triangle
maximum = 0
for x in range(0, len(sums[-1])):
if sums[-1][x] > maximum:
maximum = sums[-1][x]
print(maximum)
下面我附上了带有“数字”和“总和”arrays 的文本文件,因为如果我将它们粘贴到此处,它们会占用大量空间。
我看过发布的算法,我知道问题出在哪里。 当生成新的总和行时,它分多次执行:首先,它创建一个新的双宽度行,其中包括来自所有父级的总和。 然后它创建一个列表,其中包含每个冲突对中较小的一个。 最后,它尝试从该列表中删除值,生成最后一行。
这样做的问题是必须从行中的特定位置删除那些“坏”值,但它没有考虑到这一点,而是删除了行中每个“坏”值的第一个实例。 这有时会导致“好”值被删除,留下“坏”值。
这是一个简单的例子来证明这一点:
numbers = [
[1],
[2, 1],
[1, 2, 1],
[2, 1, 1, 1]
]
通过这个三角形的最大总和是6
,但是发布的代码错误地给出了7
。 如果您查看发布的代码产生的sums
,它们是:
[1]
[3, 2]
[5, 4, 3]
[7, 6, 5, 4]
但他们应该是:
[1]
[3, 2]
[4, 5, 3]
[6, 6, 6, 4]
我们现在可以看到这是如何发生的。 生成第三行总和时,发布的代码首先创建所有总和对:
[4, 5, 4, 3]
然后它创建“坏”列表,即:
[4]
它应该从列表中删除第二个4
,这将产生正确的行值:
[4, 5, 3]
但它反而删除了它找到的前4
,生成了不正确的行列表:
[5, 4, 3]
这可以通过限制在处理“坏”列表中的每个元素时考虑的值来解决。 但这些都不是真正必要的。 相反,在生成行时只需 select 所需的值就简单得多,从而消除了对“坏”列表的需要。 整个x
循环看起来像这样:
for x in range(1, len(sums) - 1):
for y in range(0, len(sums[x])):
temp1 = sums[x][y] + numbers[x + 1][y]
if y == 0:
sums[x + 1].append(temp1)
elif temp1 > sums[x + 1][-1]:
sums[x + 1][-1] = temp1
temp1 = sums[x][y] + numbers[x + 1][y + 1]
sums[x + 1].append(temp1)
这就是x
循环所需的全部内容。 通过此修复,它可以为原始数据正确生成7273
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.