[英]Why can't python sum properly?
我有這個代碼片段:
import math
number_of_lists, M = list(map(int, input().split(" ")))
print(sum([math.pow(max(list(map(int, input().split(" ")))), 2) for i in range(number_of_lists)]) % M)
我正在處理非常大的數字。 當我計算最終結果時,它的結果與谷歌計算器不同。 有誰知道這是為什么。 當我用谷歌計算器的值替換總和的最終值時,它會返回正確的答案。 我嘗試將其更改為 float 但沒有用,我四處尋找某種更大的數據類型,但似乎 int 應該能夠處理這些數字。
這是一個示例輸入:
7 671
7 5678403 6770488 5713245 6503478 7774748 5900452 531896
7 7728332 501199 9141815 7341382 7238970 8282671 3037527
7 7763981 7041667 3521352 9616160 7322888 5685405 6017382
7 7278231 1143649 6460915 8159948 2436146 1238439 9869216
7 1422820 9424407 4982886 7101222 8711246 696130 6121051
7 6485993 6596581 9169298 4214325 7097779 827465 4072058
7 6853100 9110135 9625936 7133432 8668153 5663640 6749591
它應該返回 670,但它返回 53。對不起,如果代碼有點擁擠,我只是想用最少的行數來解決它。 這是練習的鏈接: https ://www.hackerrank.com/challenges/maximize-it/problem?isFullScreen=true
試試這段代碼,看看它是否有幫助 - 它簡化了讀取和processing
並使其更具readable
(用於維護和調試)。
有時,我們想給人們留下深刻印象,寫出單行或緊湊的代碼,從而犧牲了可讀性。 我不建議這樣做。
import itertools as it
K, M = map(int, input(), split())
# reading the K lines and appending lists to LL
LL = []
for i in range(K):
ll = list(map(int, input().strip().split()))
LL.append(ll[1:]) # skip the first num
MAX = -1
# looping thr Cartesian Product of LL lists and get the max now
for i in it.product(*LL):
MAX = max(sum(map(lambda x: x**2, i)) % M, MAX)
print(MAX)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.