-1

I'm learning python, I want to check if the second largest number is duplicated in a list. I've tried several ways, but I couldn't. Also, I have searched on google for this issue, I have got several answers to get/print 2nd largest number from a list but I couldn't find any answer to check if the 2nd largest number is duplicated. can anyone help me, please?

Here is my sample list:

list1 = [5, 6, 9, 9, 11]
list2 = [8, 9, 13, 14, 14]
Delowar Hosain
  • 2,214
  • 4
  • 18
  • 35
  • @delowar what should the output look like ? –  Mar 08 '18 at 12:21
  • 1
    You know how to find the 2nd largest number. Do you know how to ***.count*** (hint) the number of times an element is in a list? – DeepSpace Mar 08 '18 at 12:22
  • 1
    [Literally the first google result for "python get 2nd largest number in list".](https://stackoverflow.com/questions/16225677/get-the-second-largest-number-in-a-list-in-linear-time) [Literally the first google result for "python count number of occurrences".](https://stackoverflow.com/questions/2600191/how-to-count-the-occurrences-of-a-list-item) – Aran-Fey Mar 08 '18 at 12:23
  • oh, I didn't know about .count() function. Thank you @DeepSpace – Delowar Hosain Mar 08 '18 at 12:27

4 Answers4

4

Here is a 1-liner:

>>> list1 = [5, 6, 9, 9, 11]
>>> list1.count(sorted(list1)[-2]) > 1
True

or using heapq

>>> import heapq
>>> list1 = [5, 6, 9, 9, 11]
>>> list1.count(heapq.nlargest(2, list1)[1]) > 1
True
Austin
  • 25,759
  • 4
  • 25
  • 48
0

This is a simple algorithm:

  1. Makes values unique
  2. Sort your list by max value
  3. Takes the second element
  4. Check how many occurences of this elemnt exists in list

Code:

list1 = [5, 6, 9, 9, 11]
list2 = [8, 9, 13, 14, 14]

def check(data):
    # 1. Make data unique
    unique = list(set(data))
    # 2. Sort by value
    sorted_data = sorted(unique, reverse=True)
    # 3. Takes the second element
    item = sorted_data[1]
    # 4. Check occurences
    if data.count(item) > 1:
        return True
    else:
        return False

print(check(list1))
print(check(list2))

Ouput

True
False
Arount
  • 9,853
  • 1
  • 30
  • 43
0

collections.Counter with sorted offers one solution:

from collections import Counter

lst1 = [5, 6, 9, 9, 11]
lst2 = [8, 9, 13, 14, 14]

res1 = sorted(Counter(lst1).items(), key=lambda x: -x[0])[1]  # (9, 2)
res2 = sorted(Counter(lst2).items(), key=lambda x: -x[0])[1]  # (13, 1)

The result is a tuple of second largest item and its count. It is then simple to check if the item is duplicated, e.g. res1[1] > 1.

jpp
  • 159,742
  • 34
  • 281
  • 339
0

Here is my proposal

li = [5, 6, 9, 9, 11]
li_uniq = list(set(li))               # list's elements are uniquified
li_uniq_sorted = sorted(li_uniq)      # sort in ascending order
second_largest = li_uniq_sorted[-2]   # get the 2nd largest -> 9
li.count(second_largest)              # -> 2 (duplicated if > 1)
Jal
  • 205
  • 1
  • 2
  • 8