4 回答
TA贡献1806条经验 获得超8个赞
(我把你奇怪的名字改名x为numbers。)
numbers = input().split()
numbers = [int(i) for i in numbers]
must_be = sum(numbers) / 2
if must_be in numbers:
print(int(must_be))
说明:
如果存在一个元素s使得s = (sum of other elements),
那么(sum of ALL elements) = s + (sum of other elements) = s + s = 2 * s.
所以 s = (sum of all elements) / 2。
TA贡献1825条经验 获得超4个赞
如果最后输入的数字始终是输入序列中先前数字的总和。您的问题在于 x.insert(i, y) 语句。例如,采用以下输入序列:“1 2 5 8”
after the first pass through the for loop:
i = 0
z = 15
x = [1, 2, 5, 8]
y = 1
after the second pass through the for loop:
i = 1
z = 14
x = [1, 3, 5, 8]
y = 3
after the third pass through the for loop:
i = 2
z = 12
x = [1, 3, 8, 8]
y = 8
and the for loop completes without printing a result
TA贡献1808条经验 获得超4个赞
如果保证其中一个整数将是所有其他整数的总和,您是否可以不只对输入列表进行排序并打印最后一个元素(假设为正整数)?
x = input().split(" ")
x = [int(c) for c in x]
print(sorted(x)[-1])
TA贡献1860条经验 获得超8个赞
我认为这是一个棘手的问题,可以通过使用一个技巧来快速完成,即创建一个包含所有键的字典并将总和存储为值,如 {1: 18, 3: 18, 5: 18, 9: 18}现在迭代字典,如果 val - key 在字典中,那么繁荣这就是数字
a = [1, 3, 5, 9]
d = dict(zip(a,[sum(a)]*len(a)))
print([k for k,v in d.items() if d.get(v-k, False)])
添加回答
举报