更新时间: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:
numbers[i+1:]
.先前的号码已经过检查.切片的积极作用是,列表中存在一个4
,而对于8
的目标值并没有给出一对.for
循环中对else
的理解和误解. else
仅在循环不是由break
突然结束的情况下触发.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
.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")