簡體   English   中英

我正在嘗試簡化我的代碼,但答案是錯誤的

[英]I'm trying simplify my code but the answer is wrong

這是我的代碼(正確):

 if __name__ == '__main__':
    n = int(input())
    arr = map(int, input().split())
    l = list(set(sorted(arr)))
    l.remove(max(l))
    print(max(l))

但我想這樣做(pythonic):

if __name__ == '__main__':
    n = int(input())
    arr = map(int, input().split())
    l = list(set(sorted(arr)))
    print(l.remove(max(l)))

所以..當我這樣做時,我的代碼只是打印:

打印(l.remove(max(l)))

沒有

有什么問題? 我只想簡化我的代碼。

任務:我有一個列表,我想打印第二個最高分。

看一下文檔 list.remove方法是一種就地修改列表的方法。 也就是說,它修改了您調用它的列表,而不是返回您想要的更改的新列表。

由於此函數不返回任何內容,因此打印l.remove()您“無”。 要在移除元素的情況下打印列表,您必須堅持原始代碼。

使用set()將地圖對象轉換為集合,使用sorted()將其轉換為排序列表,並使用[-2]倒數第二個元素:

print(sorted(set(arr))[-2])

我認為,這比刪除最大值然后打印新的最大值更清晰,並且可以用更少的步驟實現,因此比Python具有更多的Python風格。

您應該使用而不是排序。 您可以在O(n)時間建立一個堆,並在O(n)時間返回第k個最大項(對於任何常數k ); 排序需要O(n lg n)的時間。

import heapq

n = int(input())
arr = [int(x) for x in input.split()]
heapq.heapify(arr)   # In-place; does not return the heapified list.
print(heapq.nlargest(2, arr)[-1])

暫無
暫無

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

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