【发布时间】:2020-06-12 05:42:59
【问题描述】:
lst = [3, 4, 1, 2, 9]
givenSum = 12
table = {}
x = 0
y = 0
for i in range(0, len(lst)):
table[givenSum - lst[i]] = 1
i += 1
for x in table:
for y in table:
if (x + y) == givenSum:
print(x, "and", y, "is equal to", givenSum)
break
这是输出
9 and 3 is equal to 12
3 and 9 is equal to 12
我不知道为什么它会出现两次。我需要找到一对加起来等于给定总和的值,这是我能想到的唯一方法。我只希望它显示一次,尽管我有什么想法可以做到这一点?
【问题讨论】:
-
使用
break不输出超过一个。 (你也无用地检查反向;break会有所帮助,但它会比它需要的慢。) -
如果列表中有
6,你会怎么做? -
要解决重复问题,只需将
if (x + y) == givenSum: break添加到外循环
标签: python arrays sorting dictionary for-loop