【问题标题】:When appending a tuple to a list, I can append (a + b + c) or (a, b + c) or (a + b, c) but appending (a, b ,c) causes the program to refuse to run将元组附加到列表时,我可以附加 (a + b + c) 或 (a, b + c) 或 (a + b, c) 但附加 (a, b ,c) 会导致程序拒绝运行
【发布时间】:2021-04-09 03:48:33
【问题描述】:

这是代码

def check_right_angle(a, b, c):
    if a**2 + b**2 == c**2:
        return True
    return False

def mn_to_abc(m, n):
    return m**2 - n**2, 2 * m * n, m**2 + n**2

list_solutions = []

for i in range(1001): #Getting all primitive triples using Euclid's formula <= 1000
    list_solutions.append([])
    if i == 0:
        continue
    for m in range(1, int(i/2) - 1):
        n = int(i / (2 * m) - m)
        if m > n and n > 0:
            a, b, c = mn_to_abc(m, n)
            if check_right_angle(a, b, c) and a + b + c == i:
                list_solutions[i].append((a, b, c))

for item in list_solutions: #Getting the remaining triples by using the primitive triples
    for abc in item:
        for i in range(1, 85): # 85 since 3x + 4x + 5x = 1000 => x = 83.3333 = 84
            try:
                new_a = abc[0] * i
                new_b = abc[1] * i
                new_c = abc[2] * i
                if new_a + new_b + new_c <= 1000:
                    list_solutions[new_a + new_b + new_c].append((new_a, new_b, new_c))
                else:
                    break
            except:
                continue

print(len(list_solutions[120]))
print(list_solutions[120])

标题中主要解释了这种情况,但除非将第 30 行替换为以下任一行,否则此代码拒绝运行:

                    list_solutions[new_a + new_b + new_c].append((new_a+ new_b, new_c))
                    list_solutions[new_a + new_b + new_c].append((new_a+ new_b+ new_c))
                    list_solutions[new_a + new_b + new_c].append((new_a, new_b+ new_c))

我什至尝试将其附加为列表而不是元组,但无济于事。遇到这么奇怪的事情。

【问题讨论】:

  • 请提供堆栈错误
  • 我没有收到错误。代码只是无限期地运行。即使做 ctrl + c 也没有阻止它,我不得不关闭 vscode。我刚刚弄清楚为什么它不起作用,还是谢谢你

标签: python-3.x list tuples append


【解决方案1】:

别管伙计们,只是顿悟了。事实证明,添加到您正在迭代的列表中是一个可怕的想法。在第 30 行之前,我添加了以下代码:

if not (new_a, new_b, new_c) in list_solutions[new_a + new_b + new_c]:

您可能已经注意到,我仍在向正在迭代的同一列表中添加内容,但出于某种原因,只要该列表中的项目不重复,一切都很好。 我现在想结束这个问题,但它告诉我我只能在 2 天内接受我自己的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-12
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 2020-07-15
    • 1970-01-01
    • 2021-10-04
    相关资源
    最近更新 更多