且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从列表中找到两个数字,这些数字加起来等于一个特定的数字

更新时间:2023-02-10 17:53:14

对于列表中的每个数字,您都可以查找他的补码(该数字与前一个数字相加即可得出所需的target和).如果存在,请获取该对并退出,否则继续前进.

For every number on the list, you can look for his complementary (number that when added to the previous one would give the required target sum). If it exists, get the pair and exit, otherwise move on.

如下所示:

numbers = [2, 4, 6, 10]
target_number = 8

for i, number in enumerate(numbers[:-1]):  # note 1
    complementary = target_number - number
    if complementary in numbers[i+1:]:  # note 2
        print("Solution Found: {} and {}".format(number, complementary))
        break
else:  # note 3
    print("No solutions exist")

产生:

Solution Found: 2 and 6


注意:


Notes:

  1. 您不必检查最后一个号码;如果有一对,那么到那时您已经找到了.
  2. 请注意,由于优化了成员资格检查(在列表中这非常昂贵),因为它仅考虑切片numbers[i+1:].先前的号码已经过检查.切片的积极作用是,列表中存在一个4,而对于8的目标值并没有给出一对.
  3. 这是一个很好的设置,可以解释在for循环中对else的理解和误解. else仅在循环不是由break突然结束的情况下触发.
  1. You do not have to check the last number; if there was a pair you would have already found it by then.
  2. Notice that the membership check (which is quite costly in lists) is optimized since it considers the slice numbers[i+1:] only. The previous numbers have been checked already. A positive side-effect of the slicing is that the existence of one 4 in the list, does not give a pair for a target value of 8.
  3. This is an excellent setup to explain the miss-understood and often confusing use of else in for-loops. The else triggers only if the loop was not abruptly ended by a break.



如果即使列表中有单个 4,即使您接受4-4解决方案,也可以进行以下修改:



If the 4 - 4 solution is acceptable to you even when having a single 4 in the list you can modify as follows:

numbers = [2, 4, 6, 10]
target_number = 8

for i, number in enumerate(numbers):
    complementary = target_number - number
    if complementary in numbers[i:]:
        print("Solution Found: {} and {}".format(number, complementary))
        break
else:
    print("No solutions exist")