简体   繁体   中英

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

This is my code (It's right):

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

But I want do this (pythonic):

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

So.. when I do this my code just print:

print(l.remove(max(l)))

None

What's the problem? I just want simplify my code.

The task: I've a list and I want print the second maximum score.

Take a look at the documentation . The list.remove method is one that modifies the list in-place . That is to say, it modifies the list that you call it on, instead of returning a new one with the change you want.

Since this function returns nothing, printing l.remove() gives you "None". To print the list with the element removed, you'll have to stick with your original code.

Convert the map object to a set with set() , convert to sorted list with sorted() and take the second last element with [-2] :

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

In my opinion, this is more Pythonic than removing the max and then printing the new max as it is clearer and achieved in less steps.

You should use a heap instead of sorting. You can build a heap in O(n) time and return the k th largest item (for any constant k ) in O(n) time as well; sorting takes O(n lg n) time.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM