4 回答

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
(我把你奇怪的名字改名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))
說(shuō)明:
如果存在一個(gè)元素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貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果最后輸入的數(shù)字始終是輸入序列中先前數(shù)字的總和。您的問(wèn)題在于 x.insert(i, y) 語(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貢獻(xiàn)1808條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果保證其中一個(gè)整數(shù)將是所有其他整數(shù)的總和,您是否可以不只對(duì)輸入列表進(jìn)行排序并打印最后一個(gè)元素(假設(shè)為正整數(shù))?
x = input().split(" ")
x = [int(c) for c in x]
print(sorted(x)[-1])

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
我認(rèn)為這是一個(gè)棘手的問(wèn)題,可以通過(guò)使用一個(gè)技巧來(lái)快速完成,即創(chuàng)建一個(gè)包含所有鍵的字典并將總和存儲(chǔ)為值,如 {1: 18, 3: 18, 5: 18, 9: 18}現(xiàn)在迭代字典,如果 val - key 在字典中,那么繁榮這就是數(shù)字
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)])
添加回答
舉報(bào)