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)])
添加回答
舉報