查看列表中的一项是否是列表中其他两项的总和的最有效方法是什么?

What is the most efficient way to see whether one item of a list is the sum of two other items in the list?

该脚本应该从用户(将输入数字)处接收三个整数,并且

  1. 判断其中一个是否能被十整除
  2. 判断其中两个数是否能和剩下的数相加

我相信第一个已经完成了,但是第二个让我有点困惑。首先我做了“试错法”,虽然行得通,但根据我的口味占用了太多行,然后我尝试了这个:

num_list = [num_1, num_2, num_3]
for i in num_list:
    a = num_list.index(i)
    if i % 10 == 0:
        is_div_by_10 = True

    if i == num_list[a-1] + num_list[a-2]:
        addsUpToNumber = True

确定我的措辞不是很好,但我找不到一种方法来使用较少的代码行来获得相同的结果。

在没有太多改变的情况下,我认为你已经很接近了。不过我会把它分成两个独立的循环:

is_divisible = False
is_summable = False

num_list = [1, 2, 3]

for num in num_list:
    if num % 10 == 0:
        is_divisible = True
        break # we don't need to check the other numbers.

for i, num in enumerate(num_list):
    if num == num_list[i-1] + num_list[i-2]:
        is_summable = True
        break # we don't need to check the other numbers.

或者:

is_divisible = any(num % 10 == 0 for num in num_list)
is_summable = any(num == num_list[i-1] + num_list[i-2] for i, num in enumerate(num_list))