簡體   English   中英

我如何修復這個程序,該程序將列表中的所有整數相加,除了等於所述總和的整數?

[英]How do I fix this program that adds up all the integers in a list except the one that equals said sum?

我試圖解決一個問題,我必須輸入幾個整數作為輸入(用空格分隔),並打印所有其他整數之和的整數。

所以例如:

1 2 3 會給出:3,因為 3 = 1 + 2

1 3 5 9 會給出:9,因為 5 + 3 + 1 = 9

這是我目前擁有的代碼:

x = input().split(" ")
x = [int(c) for c in x]

y = 0

for i in range(len(x)-1):
    y += x[i]
    del x[i]
    z = sum(x)
    if y == z:
        print(y)
        break
    else:
        x.insert(i,y)

作為輸出,無論如何它什么都不提供。 有人發現錯誤嗎? 我會很高興,因為我只是一個有很多東西要學的初學者:)

(我將你陌生的名字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

如果輸入的最后一個數字始終是輸入序列中先前數字的總和。 您的問題在於 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

如果保證其中一個整數是所有其他整數的總和,您是否可以不只是對輸入列表進行排序並打印最后一個元素(假設為正整數)?

x = input().split(" ")
x = [int(c) for c in x]
print(sorted(x)[-1])

我認為這是一個棘手的問題,可以通過使用一個技巧快速完成,即創建一個包含所有鍵的字典並將總和存儲為值,如 {1: 18, 3: 18, 5: 18, 9: 18}現在迭代字典,如果 val - 鍵在字典中,那么繁榮就是數字

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)])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM