# Find the Runner-Up Score!

# Find the Runner-Up Score!

nnk94087 + 131 comments I was trying to avoid set and sort, came up with this

i = int(input()) lis = list(map(int,raw_input().strip().split()))[:i] z = max(lis) while max(lis) == z: lis.remove(max(lis)) print max(lis)

PRASHANTB1984 + 8 comments that's pretty elegant code!

Hassassin + 8 comments Hi, do you know how the max function is implemented? I'm trying to do all this challenges without using too many built in functions. (other than map for inputs)

mangatinanda + 1 comment reduce(lambda x,y: x if x>y else y, nums)

returns max element in nums list!

yashpalsinghdeo1 + 1 comment here is the solution of problem

**find the runner up score**https://solution.programmingoneonone.com/2020/06/hackerrank-find-runner-up-problem-solution-python.htmlshaifali6688 + 0 comments [deleted]

tao_zhang + 8 comments you do have a point, max() is O(n), it's not very efficient if there are many duplicated max values

jcdeargaez + 0 comments [deleted]neratisuraj038 + 21 comments @tao_zhang, here it is for many duplicated max values -

`n = int(input()) arr = list(map(int, input().split())) zes = max(arr) i=0 while(i<n): if zes ==max(arr): arr.remove(max(arr)) i+=1 print(max(arr))`

2019201058_jeev + 0 comments first=arr[0] second=0 for i in range(1,n): if first

`whats wrong here,please guide`

rikaus + 1 comment max and remove both are O(n)

gauravmishra132 + 1 comment Use a set to get O(1) complexity.

colematt + 1 comment Since Python's set abstract type is implemented as a hash table, construction of a set of

*n*items is best case (i.e. low load factor) O(*n*). Therefore first constructing a set then finding its maximum is still O(*n*).rudreshmehta9550 + 5 comments print(tuple(set(arr))[-2])

`used to find second highest value, [1,3,2,5,6,6] ans = 5 this is from FIND THE RUNNER UP SCORE. I know i can iterate through loop n find the second highest score. TEST 1 n 4 fails. Any idea?`

abedxh + 3 comments n = int(input()) arr = set(map(int, input().split())) print( list(sorted([i for i in arr]))[-2] )

shaelsingh000 + 2 comments [deleted]bhaveshlohana1 + 1 comment In array/list, it could be but, in the above code the list has been converted to set. Set doesn't have same value multiple times.

yashpalsinghdeo1 + 1 comment here is the solution of problem. https://solution.programmingoneonone.com/2020/06/hackerrank-find-runner-up-problem-solution-python.html

usman_sahi56 + 0 comments could you please explain why you take y -9999? i cant understand you logic

ukeyjayant + 0 comments To remove duplicates this function will help you:

def Remove(duplicate): final_list=[] for num in duplicate: if num not in final_list: final_list.append(num) return final_list

ar_ele=list(int(i) for i in input().split()) print(Remove(ar_ele))

Nimesh_Joshi + 1 comment it should be [-1]

bhaveshlohana1 + 1 comment The indexing starts from -1 for right to left. So if the array is sorted then, the index of second-to-last element would be -2.

rishia998 + 0 comments it will become wrong if there are two same elements in list!

yashraaj9274 + 0 comments noob

abhi3rajput + 0 comments It failed because you didn't sort the tuple. Cent percent [-2] will work if you sort it. Thanks

dopyad + 0 comments first, find the max value in array then delete it using del function, and then again find the max value from remaining array

Manjeet666 + 0 comments this is coz, your code still consists of duplicate elements.First remove duplicate elements using

*set*and then print your resultlkbhitesh07 + 0 comments 2 test case are failing here and they might be when the array is empty and when all the elements are same. All over it's a one line question any way great approach.

DeerFace + 13 comments Great solution. You could also do away with the

*'i'*variable and the*while loop*by replacing them with a*for loop*.`n = int(input()) arr = list(map(int, input().split())) largest = max(arr) for i in range(n): if largest == max(arr): arr.remove(max(arr)) print(max(arr))`

edit: fixed logical error

jishanshaikh + 2 comments Your code looks fine but there is a mistake. Try to figure out what it is.

DeerFace + 2 comments oops, nice catch. I must have copied and pasted the code I was messing with rather than the finished code. It's fixed now.

sjayanthkumar191 + 0 comments ok good kuck

[deleted] + 0 comments Can you share the fixed code?

sjayanthkumar191 + 0 comments he figured out that

enji_py + 9 comments Your code will show error because when largest number is removed in one iteration, then the next number will be assigned it's index and thus it will become a mess. you could try this

`n = int(input()) arr = list(map(int, input().split())) a = max(arr) for x in range(len(arr)-1,-1,-1): if arr[x] == a: arr.remove(arr[x]) print(max(arr))`

DeerFace + 0 comments What were the examples that you used that raised an error? I'd like to check it out.

MR_MECHANICAL + 14 comments # your error wont occurs here

if

**name**== '**main**':`n = int(input()) arr = list(map(int, input().split())) listnew=[] for i in arr: if i not in listnew: listnew.append(i) listnew.sort(reverse=True) print(listnew[1])`

Sanketpathak64 + 2 comments hey I am new to python here.can u tell me what is significance of map keyword while taking inputs.

balavemulakonda + 1 comment python map() is an iterator.so that we can iterate over elements. can be converted to tuple ,lists

sjayanthkumar191 + 2 comments map is also very usefull to use lambda functinons and it applies function to all items in the input list

balavemulakonda + 0 comments yes!!one more point!!

colematt + 0 comments Not to be picky, but for

`map(function, iterable, ...)`

, the argument*iterable*can be any object capable of returning its members one at a time, not just lists. For example,`map(lambda x:x*x, range(10))`

yields an iterable of the first ten perfect squares.

Roei_M + 0 comments Thanks ! Was very helpful

gade0676 + 1 comment it wont work for multiple max value...

sonofhotmale + 0 comments When I tested a few custom test cases with multiple custom values and they passed. Unless, you think there's a test case I missed? If so, I'm curious which test case would this fail?

udaykumar_bejjam + 1 comment for every element you are checking the list for its existance which iterates list every time. so it may not so efficient.

raohemantkalgan1 + 1 comment yes, thats why you should try this

n=int(input()) l1=list(map((int),input().split())) l2=sorted(list(set(l1))) print(l2[-2])

lakshmanpraveen1 + 0 comments Hello , can you expain it clearly cause i want to understand how to write in a single line like you.

vidhikumar2000 + 0 comments Amazing!! Simplicity at its best

tug03036 + 1 comment Wow did not understand this for a hot second. S/o you though, this is good stuff imo even though my opinion as a noob isn't much.

bhaveshlohana1 + 2 comments Try this:

n = int(raw_input()) arr = map(int, raw_input().split()) arr=sorted(list(set(arr))) print(arr[-2])

jaybhingradiya7 + 0 comments thanks for guiding me. :)

tamer_zedan_abd1 + 0 comments [deleted]

swapnaj_nandgao1 + 0 comments nusta indentation error...

shriramjadhav + 0 comments This code will fail if largest number occures multiple time.

hp_well + 1 comment You'll get the wrong anwser if we have the list with all same values. Ex: [1, 1]

IndexError: list index out of range

ramseshu_cool + 0 comments List with same numbers wont have second largest number.

Tharim + 0 comments goog job ! really helpful , Danke schÃ¶n...

robinrodrigues61 + 0 comments [deleted]yavishalrai + 0 comments thnaks bro good job

neromnkdy + 0 comments haha if name='main' good luck

shreytrivedi577 + 0 comments Nice Logic

jaybhingradiya7 + 1 comment n= int(input()) arr = map(int, input().split())

a = list(arr) b = max(a) c=[]

for i in range(len(a)): if a[i]==b: continue c.append(a[i])

print(max(c))

bhaveshlohana1 + 0 comments It is a lengthier approach, you can convert the list to set to remove duplicates.

n = int(raw_input()) arr = map(int, raw_input().split()) arr=sorted(list(set(arr))) print(arr[-2])

MANOJ_180030342 + 0 comments very nice code . Thanks

maitrijha297 + 1 comment can you pls explain why -1,-1,-1 ??

sjayanthkumar191 + 0 comments thats nothing just for counting the nums from reverse...

raohemantkalgan1 + 1 comment no need to find largest number n=int(input()) l1=list(map((int),input().split())) l2=sorted(list(set(l1))) print(l2[-2])

er_arunkumar + 0 comments solve this please for me:

in file handling python FI FILE HAS = A B C ; F2 FILE HAS:--- P, Q , R ;

file fif2 should be like a=p , b= q = c=r

try anyone who is intersted

solve F1F2:- A=P B=Q C= R

janani_sekar1303 + 0 comments could u elaborate the 4th and 5th line?

mishra_divyansh + 1 comment def y(x): return set(x)

n=int(input()) list1=[] for i in range(n): k=int(input()) list1.append(k) list1.sort() j=y(list1)

whats wrong

b=len(j) def chiku(x): return list(x) list2=chiku(j) print(list2[b-2])

er_arunkumar + 0 comments solve this please for me:

in file handling python FI FILE HAS = A B C ; F2 FILE HAS:--- P, Q , R ;

file fif2 should be like a=p , b= q = c=r

try anyone who is intersted

solve F1F2:- A=P B=Q C= R

mohit_sharma3105 + 0 comments use set instaed of list

usman_sahi56 + 0 comments hy could you explain itration of for loop kindly

shivvu123 + 0 comments can you plz, tell me what was the error in your code before fixing it.

kaushikchowdary2 + 0 comments [deleted]diogovguedes + 0 comments Thanks for this! Very clear

MR_MECHANICAL + 6 comments # use it

if

**name**== '**main**':`n = int(input()) arr = list(map(int, input().split())) listnew=[] for i in arr: if i not in listnew: listnew.append(i) listnew.sort(reverse=True) print(listnew[1])`

jenimurugan12697 + 0 comments Simple and super

Code_Vee + 1 comment can u please explain it to me

MR_MECHANICAL + 8 comments **

`n = int(input()) arr = list(map(int, input().split())) listnew=[] for i in arr: if i not in listnew: listnew.append(i) listnew.sort(reverse=True) print(listnew[1])**`

1st we are getting size of the array from the user (but we re not gonna use it anyway) then we are getting the elements of the array it is to be noted that all the elements are in a single line seperated by "space"

**arr=list(map(int, input().split()))**what this code does is that it takes the input and by default ".split()" method split the input with respect to space if you want any other insted like comma "," of spce you can specify it like this " input().split(",") " .since the input function always returns a string to convert the string to int we use map . map is just like a loop it takes value after comma and force it to change it type with what we specify before comma. "map(what to do the value,value)" .finally we are taking all those mappped int value and putting it inside a list.

**

`listnew=[] for i in arr: if i not in listnew: listnew.append(i)`

listnew.sort(reverse=True)

print(listnew[1]) **

we are creating a new list "listnew" you will know why we have created it later . now we are taking all the values in arr and assaigning it to i from begning using a for loop now if i is not in new list we are appending the value of i to new list we are doing this to eliminate duplicate values the last two lines are used to reverse the list so that the 1st number will be the winner score and we print " listnew[1] " which is the runner up score

ozencmustafa + 0 comments Thanks

naik2191 + 0 comments Great!!

doomed_fellow + 0 comments how the maximum value comes first in the new list? I meant how it arranged itself in ascending order before you reversed it use listnew.sort(reverse=True)

yashbhalgat9657 + 0 comments great help

jami_sk01 + 0 comments this is called perfect lecture with handson.

er_arunkumar + 0 comments solve this please for me:

in file handling python FI FILE HAS = A B C ; F2 FILE HAS:--- P, Q , R ;

file fif2 should be like a=p , b= q = c=r

try anyone who is intersted

solve F1F2:- A=P B=Q C= R

nikhilvkn + 0 comments i have a doubt here, we are taking the value for

`n`

from user. If in this code I am starting to put value, I can put 5 for`n`

, but I can do 10 or 20 values for`arr`

can you update where you can add only`n`

elements taken from the user?shashidhar_sy + 0 comments perfect

kolwalkaramod96 + 1 comment Why are we using not in?

MR_MECHANICAL + 2 comments **

`n = int(input()) arr = list(map(int, input().split())) listnew=[] for i in arr: if i not in listnew: listnew.append(i) listnew.sort(reverse=True) print(listnew[1])**`

1st we are getting size of the array from the user (but we re not gonna use it anyway) then we are getting the elements of the array it is to be noted that all the elements are in a single line seperated by "space"

**arr=list(map(int, input().split()))**what this code does is that it takes the input and by default ".split()" method split the input with respect to space if you want any other insted like comma "," of spce you can specify it like this " input().split(",") " .since the input function always returns a string to convert the string to int we use map . map is just like a loop it takes value after comma and force it to change it type with what we specify before comma. "map(what to do the value,value)" .finally we are taking all those mappped int value and putting it inside a list.

**

`listnew=[] for i in arr: if i not in listnew: listnew.append(i)`

listnew.sort(reverse=True)

print(listnew[1]) **

we are creating a new list "listnew" you will know why we have created it later . now we are taking all the values in arr and assaigning it to i from begning using a for loop now if i is not in new list we are appending the value of i to new list we are doing this to eliminate duplicate values the last two lines are used to reverse the list so that the 1st number will be the winner score and we print " listnew[1] " which is the runner up score

sukuya + 0 comments First you are running for loop on arr, so best case complexity is O(n). Then there are check on entire new list for each iteration, which will make your algo ~ O(n^2)

dude_yashwant2 + 1 comment But If you have same elemensts in first two indexs this code won't work

jami_sk01 + 0 comments he eliminating the duplicacy, so his code works. he wrote very simple and proper code.

rarsrikar + 0 comments i had a doubt in map function in the above program. While iam trying the liist through map function in our IDLE it is giving only one value.I cant rectify the problem. Can you please explain?

er_arunkumar + 0 comments solve this please for me:

in file handling python FI FILE HAS = A B C ; F2 FILE HAS:--- P, Q , R ;

file fif2 should be like a=p , b= q = c=r

try anyone who is intersted

solve F1F2:- A=P B=Q C= R

somyagoyaljtti + 0 comments [deleted]

jalajgupta001 + 1 comment can anyone please explain this code

MR_MECHANICAL + 0 comments **

`n = int(input()) arr = list(map(int, input().split())) listnew=[] for i in arr: if i not in listnew: listnew.append(i) listnew.sort(reverse=True) print(listnew[1])**`

1st we are getting size of the array from the user (but we re not gonna use it anyway) then we are getting the elements of the array it is to be noted that all the elements are in a single line seperated by "space"

**arr=list(map(int, input().split()))**what this code does is that it takes the input and by default ".split()" method split the input with respect to space if you want any other insted like comma "," of spce you can specify it like this " input().split(",") " .since the input function always returns a string to convert the string to int we use map . map is just like a loop it takes value after comma and force it to change it type with what we specify before comma. "map(what to do the value,value)" .finally we are taking all those mappped int value and putting it inside a list.

**

`listnew=[] for i in arr: if i not in listnew: listnew.append(i)`

listnew.sort(reverse=True)

print(listnew[1]) **

we are creating a new list "listnew" you will know why we have created it later . now we are taking all the values in arr and assaigning it to i from begning using a for loop now if i is not in new list we are appending the value of i to new list we are doing this to eliminate duplicate values the last two lines are used to reverse the list so that the 1st number will be the winner score and we print " listnew[1] " which is the runner up score

temirlanmirzakh1 + 1 comment It seems to me that your code is O(n^2) in the worst case due to the following reasoning: -Assume we have the worst case like [5,6,6,6,...,6]- an array consisting almost fully out of sixs. -Then your for-loop will work n-times calling max(arr)-function, which takes O(n). -So we can say that it's O(n^2) in the worst case, while I can provide the solution with O(n) in this case, even though it's less elegant and requires the creation of some more temporary variables to store the max and second highest value. -Then can you still claim that your code is the most effective? Please, correct me if I'm wrong, I would really appreciate that.

er_arunkumar + 0 comments solve this please for me:

in file handling python FI FILE HAS = A B C ; F2 FILE HAS:--- P, Q , R ;

file fif2 should be like a=p , b= q = c=r

try anyone who is intersted

solve F1F2:- A=P B=Q C= R

ashwinpatnaikcr7 + 1 comment why did you add list here?

MR_MECHANICAL + 0 comments i am not adding any list just created a list and inserted value inside it to avoid duplicate element you can also use set over there but you cant find max element in it

rakshitrao + 0 comments If i replace max(arr) to arr(i) inside the for loop , i don't get the expected output.

saimon_assuncao + 1 comment @DeerFace, good tip! cheers!

naik2191 + 0 comments [deleted]

raohemantkalgan1 + 0 comments n=int(input()) l1=list(map((int),input().split())) l2=sorted(list(set(l1))) print(l2[-2])

rnishant208 + 0 comments @DeerFace I am not getting the second line, can you please explain?

sjayanthkumar191 + 1 comment the line 6 is error

rishadkhan670 + 0 comments Same to my bro

krishnasandeep01 + 1 comment Traceback (most recent call last): File "solution.py", line 7, in res=max(arr) ValueError: max() arg is an empty sequence

`I am gettin this error for same code. Bro plz help me`

sona0110 + 0 comments I am also getting same error. however its res==max(arr)

sravan234 + 1 comment this code willl get error remove function remove the index values not the max value to remove you want to caluclate the max value index and we want to remove it.

balavemulakonda + 0 comments can u plz keep the snippet of ur code?

h953618106027 + 0 comments [deleted]jalajgupta001 + 0 comments can anyone explain this code

trivedibhavik411 + 0 comments use set instead of list

[deleted] + 0 comments [deleted]jenimurugan12697 + 0 comments Thank u for your solution...It is very helpful for python beginner like me

raohemantkalgan1 + 0 comments n=int(input()) l1=list(map((int),input().split())) l2=sorted(list(set(l1))) print(l2[-2])

durga_9 + 0 comments can you please explain the while loop here.why are you not using 'i' in if condition.I dint understand how zes==max(arr) is working without using i

RJ_BANNA + 1 comment [deleted]RJ_BANNA + 1 comment Your cont won't work on input of 0 0 0 0 0

You would need to add below condition

if len(arr) > 0: print(max(arr))

sjayanthkumar191 + 0 comments in this case it dosent need

pratishthasoni + 0 comments hey... i m new to python, we can directly take the input thn why are we applying aplit adn map functions

akshatha20_shet1 + 0 comments [deleted]akshatha20_shet1 + 0 comments [deleted]Reviksedy + 0 comments Hmm i am beginner but i wrote code in 6 lines

brandon_lw_bish1 + 0 comments Could you not turn the list into a set to deal with multiple values?

rajdeepkalita09 + 0 comments Can u pls explain why did u used list here

suyograne097 + 1 comment I just Loved the logic that u have used.

sjayanthkumar191 + 0 comments thanks

dnchippa + 0 comments Yes, alternatively you can use sort function at start and then pop elements until it is not equal to first popped element.

trivedibhavik411 + 0 comments just use set instead of list...it will save only one value for multiple values ..

avinas_nayak + 0 comments [deleted]avinas_nayak + 0 comments we can use count() to check number of occurances of max value:

n = int(input())

arr = map(int, input().split())

list1=list(arr)

max1=max(list1)

max_no=list1.count(max1)

[list1.remove(max1) for i in range(0,max_no)]

print(max(list1))

barunsharma_mait + 0 comments if

**name**== '**main**': n = int(raw_input()) arr = map(int, raw_input().split()) arr = list(set(arr)) arr.sort(reverse = True) print(arr[1])this would be efficient as we would be removing duplicate values.

colematt + 0 comments Using the reduce() function like this does not yield any improvement. In fact, it's almost 10x slower than just using the built-in max() function. Here's proof: Github Gist

DoctaCloak + 1 comment I was trying to use max as well... @nnk94087 has really beautiful code man!

BrookTaylor + 0 comments There's a small bug that could occur if all the entries are the same for n. I.e. if n = 2, and the list contains [1, 1] for scores, it will not evaluate. You'll need to add something along these lines in order to get around those cases; here's what I came up with.

i = int(input()) lis = list(map(int,input().split())) [:i] z = max(lis) if lis.count(lis[0]) == len(lis): print(max(lis)) else: while max(lis) == z: lis.remove(max(lis)) print(max(lis))

preetkewl + 0 comments I am trying same.

daniel_augusto11 + 0 comments def func_maximo(): maximo = Lista[0] for z in range(len(Lista)): if Lista[z] > maximo: maximo = Lista[z] return maximo if __name__ == '__main__': #Declarnado Variavel n = int(input()) arr = map(int, input().split()) # Tudo em Lista Lista = [] for x in arr: Lista.append(x) # Maior Numero x = func_maximo() # Removendo o maior numero while func_maximo() == x: Lista.remove(x) # Printando o segundo maior numero apos remover print(func_maximo())

Vivek1201 + 0 comments yess u can do this without max funtion using sorting .fristly convert it into list then sort the list and print the second element , that will be the runnerup..

gautamcs22 + 0 comments I found the easiest to find the max by this without using any pre defined function. "" def get_max(arr): if len(arr): max = arr[0] for i in arr: if i > max: max = i return max """

c_sahmuradov + 0 comments n = int(input()) arr = list(map(int, input().split())) negatives = [-1,-2,-3,-4,-5,-6,-7,-8,-9,-10] d = [] for i in arr: if i in negatives: d.append(i) d.sort()

d.reverse() c = [] for i in arr: if i not in c: c.append(i) c.sort() print(c[-2])

*

moglobal + 40 comments How about this shorter one...

n = int(raw_input()) nums = map(int, raw_input().split()) print sorted(list(set(nums)))[-2]

hyankov + 5 comments Hi, I believe this code is correct only in the cases where the max number apears only once in the input.

Considering the following input [1, 2, 2] it would return 2 whereas it should return 1.

moglobal + 14 comments You can try it! :)

nums = [1, 2, 2] print sorted(list(set(nums)))[-2]

Prints '1' for me. The 'set' function returns only unique values (here, [1, 2]), and then after sorting, the second to last element is printed.

hyankov + 2 comments Oops, my bad - I missed you were using set prior sorting. Nevermind - it looks great!

santosheswaran + 5 comments 5

-7 -7 -7 -7 -6

for this input i think your code wont wholes good

albert18 + 3 comments This code doesn't work for test case 5 -7 -7 -7 -7 -6 because his while he takes the input as lis the elements in it are strings not integers so you've to convert those elements into integers and then run the code.

N= input() L= raw_input().split() I=[] assert N>=2 and N<=10 for i in L: I.append(int(i)) I.sort() largest=max(I) count=I.count(largest) for i in range(count): I.remove(largest) print max(I)

tcloaa + 0 comments His code works. You should try it again dude

nick3499 + 0 comments [deleted]achintya0210 + 1 comment Works in python 2 only

kenyurgel22 + 0 comments it worked in python 3 too

23editorcs + 0 comments [deleted]23editorcs + 1 comment It still works. I just checked.

KeyurPotdar + 1 comment [deleted]salvadharani_84 + 0 comments [deleted]

bONSPARROW + 0 comments it works.

suryansh_vimale1 + 0 comments his code would work for this input , as he is using sets concept in this , the number arent repeated in sets .

jzhou3000 + 2 comments How about the case like this: 3 5 5 5 set(nums) will only return one element, [-2] will out of index.

jzhou3000 + 0 comments I mean 3 numbers: [5, 5, 5]

Benish + 0 comments GO WITH THIS which does it include any sort or set func ...T.C of O(n) rather than O(logn) for sorting it

if

**name**== '**main**': n = int(input()) arr = map(int, input().split()) list1 = list(set(arr)) max=max(list1[0],list1[1]) secondmax=min(list1[0],list1[1])`for i in range(2,len(list1)): if list1[i]>max: secondmax=max max=list1[i] else: if list1[i]>secondmax: secondmax=list1[i] print(secondmax)`

vikasbiet3 + 6 comments what [-2] does please explain.

salernoa + 1 comment Refers to the second to last element.

konidala_venky11 + 3 comments what if there is a repetition of the max number -2 wont work there

ahmetenessemerci + 0 comments code uses a set(only distinct numbers)

sourabhsinha396 + 0 comments Set can have only non-repeating values

sourabhsinha396 + 0 comments Set can have only non-repeating values

Forbidden_Devil + 0 comments The list can be accessed from last, considering last element of index -1 and second last element of index -2 and so on...

kishornawal13 + 0 comments like we have list=['1','4','6','7'] then [-1]=7 and similarly [-2]=6 that all.

siAyush + 0 comments [-2] this is indexing in this case it is used to find number which is second largest number after sorting the list

iMems + 0 comments that's the second item of the list from the right. for example: if you have a list=[1,4,6,9,11] list[-1] returns 11 list[-2] returns 9

sourabhsinha396 + 0 comments -ve index signifies starting from last index

Unastic + 1 comment I think you don't need sorted, works just fine without it.

bONSPARROW + 0 comments you cannot be sure about that. set returns unordered collection of unique elements from the iterable. we cannot be sure about the output of set() as it is unordered and need not be sorted. sorted() is required to return a sorted list from the unordered set. maybe it worked for you but it cannot be guaranteed to work everytime. the list() function is redundant as sorted() returns a list itself.

abhijain1351 + 2 comments What would your code do for Input [2,2,2,2]

Divan_Cyph + 0 comments Use Try and Except

rohan_killedar + 1 comment Index out of bound as [-2] index doesnt exists when you use set

Benish + 0 comments set does not consist of indices

sanyenoh + 0 comments moglobal thats one of the best code ive ever seen.. great job!!!

bONSPARROW + 0 comments you don't need the extra list() function as sorted returns a new list itself.

okanozdemir + 0 comments dn,arr=(input() for _ in range(2)) nums = map(int, arr.split()) a=sorted(list(set(nums))) if(len(a)==1): print(a[0]) else: print(a[-2])

to avoid [1, 1, 1] or just [1]

Code_Lord + 0 comments [deleted]vaibhavg12 + 0 comments pretty cool. thanks for sharing. I had the same intent but missed the set/duplicate part.

rmkhr048 + 0 comments Why do we need "list" here?

jatin345anand + 0 comments Correct bro,Set is able to store only non-duplicate....

celestial5150 + 1 comment Very nice, learn something new everyday, very pythonic :)

sjayanthkumar191 + 0 comments thnq

ragurampandiyan6 + 0 comments Not Working for me!

deepapatil7354 + 0 comments very simple to understand and easy way to code...

tewarimukul + 0 comments I think its correct as set will remove duplicate values

kaivanshah1663 + 0 comments but set would return unique elements i guess

sharmavikku14 + 0 comments I think set() will delete duplicate values. so [1,2,2] will be reduced to [1,2]

Anuradhabharti6 + 0 comments he use set datatype

istewartbinks + 2 comments nlog(n) though.

jordancar + 0 comments no,BFPRT,O(n)

gaudham1998 + 0 comments try this @R)Try&i

maximshen + 3 comments I was trying to convert set to list like you did. But I noticd you could just use sorted() for the set ! Weird, but it works just fine ...

input()myList = sorted(set(map(int, input().strip().split()))) print(myList[len(myList)-2])

zhangtreefish + 0 comments Cool. Not weird, since sorted creates a copy during the sort, so even an immutable thing like set is granted operation.

Alexhans + 2 comments I did a similar thing:

`input() print(sorted({int(x) for x in input().split()}, reverse=True)[1])`

edit (With one less call, don't reverse sort):

`sorted({int(x) for x in input().split()})[-2]`

braininahat + 0 comments [deleted]prachi_waghmare1 + 0 comments print(sorted(set(l))[-2]) this works

Dim_S + 0 comments Just myList[-2] - is shorter and still correct.

ZachPerkitny + 0 comments [deleted]ZachPerkitny + 0 comments [deleted]satadhi + 1 comment hi can you tell me please where the value of n is being used and how ? thanks any ways

sankalpgupta13 + 0 comments n is nowhere to be used

COD_TLS100011 + 1 comment Can you please tell what map() is doing here ?

maximshen + 0 comments map(function, iterable, ...)

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.

https://docs.python.org/2/library/functions.html#map

SuperGogeta + 2 comments List isn't necessary as sorted takes any object iirc

print raw_input()==0 or sorted(set(map(int, raw_input().split())))[-2]

For those that didn't understand, first input isn't actually necessary because validation of the length of the numbers entered in 2nd line isn't actually being asked

raw_input returns type string, hence it will never be zero(0) and won't print the first input under any circumstance.

Next read the input,split away the spaces and map it to integer type

Make it's set

Sort the set

Print the 2nd last element in the sorted set

Max_Vignesh + 1 comment Thank you so much.. superGogeta

Thanks & Regards

SuperGogeta + 0 comments Camel casing my name lol, Your welcome :)

Gurupad + 0 comments Nice. My code is same as yours except you handled unnecessary

`n`

input in one line :)

kosuke_ueki91 + 0 comments I was able to do it in one line. But I will not tell you how! Try to figure it out yourself HA HA

ANISH98 + 2 comments Can anyone plz explain why sorted() works and not the function sort() ?

evandam92 + 0 comments My understanding is that sorted() returns a new sorted list, and also works for things besides lists (map objects, tuples, etc.). list.sort() sorts a list in place.

Gurupad + 1 comment You can use

`sort()`

it is efficient than`sorted()`

as it does in-place sorting. They used sorted, so that they write it in lesser number of characters.`sort()`

returns`None`

whereas`sorted()`

returns the newly created list.Using

`sort()`

:n=input() nums=set(map(int),input().split()) nums.sort() #here in-place sorting takes place print (nums[-2])

patrick_x99 + 1 comment 'set' object has no attribute 'sort'

matthewrlefevre + 0 comments ^ This. The set function doesn't create a list, and sets don't allow for the sort attribute. Using sorted() converts the data into a list, then sorts it.

mike627 + 0 comments [deleted]kurian_benoy + 0 comments won't work if 6,6 element are the largest in list

KeyurPotdar + 0 comments [deleted]danielgcwik + 0 comments thanks it worked for me.

surfer2047 + 1 comment even without using list

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

prachidwivedi + 1 comment can you explain [-2]

dbchernyak + 0 comments seond from the end

rakshanihamad + 0 comments Can you please explain it. Code worked like magic. I am new in python. So I need to get it clear in my head ASAP!

hagayo + 0 comments Good one moglobal!

livelikekrishna + 0 comments if enter n=6 and give 10 elements then will get wrong. ur code is not using n

guptashuboyoo7 + 1 comment hy can u tell me about what set is exactly works in set(nums)?

atchyutn + 0 comments It returns list with unique values.

eduardo_prz_gmz + 3 comments Nice, I didn't think of the set function. Here is my aproach:

if __name__ == '__main__': n = int(input()) arr = map(int, input().split()) list = list(arr) l = [x for x in list if x != max(list)] print(max(l))

jae_duk_seo + 0 comments This is very interesing solution

goyalnitin634 + 0 comments Its always good to see List Comprehensions. But don't you think this will increase overall runtime ? I mean you are creating a new list and then finding the max. of it!

sonofhotmale + 0 comments Nice! Here's an even shorter version using your approach:

if

**name**== '**main**': n = int(input()) arr = list(map(int, input().split())) print(max([x for x in arr if x != max(arr)]))

mikee531 + 1 comment dude where are we using n here??

tarandeeps1197 + 0 comments Actually 'n' is used here to iterate 'arr' object

arr = map(int,input().split())[:n];

and

arr = map(int, input().split());

are same

Hope this helps!

mazhuo79 + 0 comments This is a great solution.

mahatma + 0 comments This fails if u had more than 2 numbers of maximum value in the given list

gairukabasnayaka + 0 comments It is wonderful broo

[deleted] + 0 comments it can also be written like this, n = int(raw_input()) nums = map(int, raw_input().split())

print sorted(list(set(nums)),reverse=True)[1]anany_boss + 0 comments you dont need to convert it into list! sorted(set(nums))[-2] works fine even with negative numbers

angelw1961 + 0 comments I really think I understand this answer... I was thinking of max but this one makes more sense to me.

I have mostly worked in python 2.7 and am trying to refresh my knowledge of it while updating to 3.0 is there documentation on the sorted() and hot to use it that is easy to understand?

MaxNRG + 1 comment Python 3 version:

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

shaelanderchauh1 + 2 comments what if i want to print the max no as well as second max no ?

baojianfei1208 + 0 comments [deleted]baojianfei1208 + 0 comments you can use:

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

just try it

premchandmsd07 + 1 comment what does the function set()do?

MaxNRG + 0 comments make set :)

anirbanghoshsbi + 0 comments I get an a error list object is not callable , however it works if I remove the list keep sorted(set(nums))[-2]

praveen_nagaraj3 + 0 comments set defines what ,. sort used to assing in ascending order ,list fn is to print the mapped object. for this set ,how it is assing for this particular output

ankush25kumar + 0 comments wow that was smooth... why i didnt think that way... lol i always choose long path

thenextgalileo + 0 comments Good answer. It can be done without casting to a list:

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

kaivanshah1663 + 0 comments [deleted]eloyekunle + 0 comments Although I don't see why you had to apply

`list`

to the`set`

.mchougule297 + 0 comments that's cool dude

ellin33 + 0 comments This worked neatly for me. The only thing I'll add are paranthases wrapped around the print statement because I was getting errors without them:

n = int(input()) arr = map(int, input().split()) print (sorted(list(set(arr)))[-2])

kuldipsinh_jam + 0 comments Really awesome logic.

vitorcvargas + 0 comments Very nice! So smooth!

I didn't understand why you used sorted()... I thought set() already did that.

Sorry... new in python...

Thanks!

joylensaldanha + 0 comments why do we use the strip() function? won't it work just fine with only the split() function? Thanks

Bansal_P + 2 comments Another method can be :-

n=int(raw_input())

a=map(int,raw_input().split())

a.sort()

w=a.index(max(a))

print a[w-1]

Options_Guru + 1 comment I like this solution

balaji_m_2016_c1 + 0 comments [deleted]

IamSuRjya + 0 comments This wont work on Python 3.

pedroferreira_11 + 1 comment and what do you think about this one line code solution: print (input() and None) or sorted(list(set(map(int, raw_input().split()))))[-2]

gundoganfa + 0 comments I don't understand at all.

hapylestat + 0 comments not at all, quite unstable

sharq + 0 comments This code also works

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

rikaus + 0 comments nothing So beautiful

purushoth + 5 comments a = int(input())

b = (raw_input().split(" "))

b.sort() #-----> sort is not working for negative numbers here only any idea ??

print b

b.reverse()

print b

for i in range(len(b)):

`if b[i] < b[0]: print b[i] break`

Hassassin + 1 comment I always use my costum sort, you can try it. Also, a while seems better than a if+break. ...And you can do reversed(xrange(len(b)).

`def qsort(A): if len(A)<=1: return A return qsort([x for x in A if x<A[0]])+[x for x in A if x==A[0]]+qsort([x for x in A if x>A[0]])`

kishor143mbl + 0 comments Can you pls explain how this works??

aa1992HackerRank Admin + 1 comment Its working for negative numbers.check this

`N=int(raw_input()) list=list(set(map(int,raw_input().strip().split(" ")))) list.sort(reverse=True) print list[1]`

amanagarwal2189 + 0 comments [deleted]

motox2 + 0 comments First, convert the elements b to integers . Your sorting should work then. Right now , it is sorting on strings not on integers.

Omkark123 + 1 comment sort wont work because you are taking a string. try to use map and map int function on your list.

letitslide87 + 0 comments [deleted]

simonotter + 0 comments @purushoth it is because you have not converted your list of strings to int

b = (raw_input().split(" "))

should be

b = map(int,raw_input().split())

also note that .split() defaults to splitting on spaces e.g. " "

gtorrecilla + 1 comment The problem with this implementarion is the complexity. You are doing it in O(nÂ²), while you can do this in O(n). Even sorting the list have a better complexity O(n*log(n)). An example of a patological case is the list [5, 5, 5, 5, 5 ,6] or something like that.

bicole + 2 comments gtorrecilla. What do you think of this? Its not the best by line count, but I believe it finds the 2nd largest within O(n).

`max = max2 = -100 - int(raw_input()) nums = map(int,raw_input().split(' ')) for i in range(len(nums)): if nums[i] > max2: if nums[i] > max: max,max2 = nums[i],max elif nums[i] < max: max2 = nums[i] print(max2)`

omnius42 + 0 comments You're doing a bit more work than you need to. Instead of iterating over a range, just iterate over the number list.

`raw_input() max = max2 = -101 for n in map(int,raw_input().split()): if n > max2: if n > max: max,max2 = n,max elif n < max: max2 = n print(max2)`

evandam92 + 2 comments I think this is the best approach too to stay within O(n). My solution was something similar:

n = int(input()) a = [int(x) for x in input().split()] largest = secondlargest = -100 for x in a: if x > largest: tmp = largest largest = x secondlargest = tmp elif x > secondlargest and x != largest: secondlargest = x print(secondlargest)

somewhatabstract + 2 comments You don't need that tmp var, just reorder your first condition:

n = int(input()) a = [int(x) for x in input().split()] largest = secondlargest = -100 for x in a: if x > largest: secondlargest = largest largest = x elif x > secondlargest and x != largest: secondlargest = x print(secondlargest)

youngshawzju + 0 comments works!but a little improvement is needed

zsts0 + 0 comments Python O(N) solution with no hardcoding the number below minimal:

if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) runner_up = first = arr[0] for i in arr[1:]: if i > first: runner_up, first = first, i continue if runner_up < i < first: runner_up = i elif i < runner_up == first: runner_up = i print(runner_up)

RaduAlexandruB + 0 comments [deleted]

paul_schmeida + 0 comments Very nice, but max() is a built-in function just like sorted() :P I've come up with this two liner using sorted(), set() and listcomp instead of map():

n, a = int(raw_input()), list(set([int(x) for x in raw_input().split()])) print sorted(a)[len(a)-2]

dennysregalado + 0 comments It was a clear solution, you don't need calculate the largest number over and over, just use

lis.remove(z)

inside the loop.vartaks + 5 comments Even more Pythonic way to do it would be as follows:

N = int(raw_input())

arr = map(int, raw_input().split())

print max([x for x in arr if x != max(arr)])

paul_schmeida + 2 comments I think "pythonic" is an overused word :) Anyways I did a profile on those two implementations:

from profilehooks import profile @profile def snd_largest_0(): n, a = int(raw_input()), list(set([int(x) for x in raw_input().split()])) return sorted(a)[len(a)-2] @profile def snd_largest_1(): n = int(raw_input()) arr = map(int, raw_input().split()) return max([x for x in arr if x != max(arr)]) print snd_largest_0() print snd_largest_1()

*** PROFILER RESULTS *** snd_largest_0 (E:/python_projects/hello_world/second_largest.py:6) function called 1 times 7 function calls in 1.633 seconds Ordered by: cumulative time, internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 1.633 1.633 second_largest.py:6(snd_largest_0) 2 1.633 0.816 1.633 0.816 {raw_input} 1 0.000 0.000 0.000 0.000 {sorted} 1 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects} 1 0.000 0.000 0.000 0.000 {len} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 0 0.000 0.000 profile:0(profiler) *** PROFILER RESULTS *** snd_largest_1 (E:/python_projects/hello_world/second_largest.py:12) function called 1 times 12 function calls in 1.862 seconds Ordered by: cumulative time, internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 1.862 1.862 second_largest.py:12(snd_largest_1) 2 1.862 0.931 1.862 0.931 {raw_input} 1 0.000 0.000 0.000 0.000 {map} 6 0.000 0.000 0.000 0.000 {max} 1 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 0 0.000 0.000 profile:0(profiler) Process finished with exit code 0

My code read everything in one go then just returns and every function or method is called only once (total of 7 function calls).

Your code on the other hand has 12 function calls and calls max() for every element in the list. Also, according to PEP, variable names should start with lowercase, so N should be n.

I suppose I could use map to change list elements to int, but in this case list comprehension is almost as fast.

vartaks + 0 comments Thanks for the clear and concise comparison!

tarathedev + 0 comments Is there a reason you wouldn't just store max(arr) in a separate variable first and use that in the list comprehension so that it's not called multiple times? Seems like a simple solution to reduce the number of calls.

gabrielsuprememe + 0 comments I did mine similarly, but with filter.

input() a = map(int, raw_input().split()) max_value = max(a) a = filter(lambda x: x != max_value, a) print max(a)

vjay_b5 + 0 comments This wont work in python 3 , but works in python 2

Duboyal2 + 0 comments [deleted]Midge + 2 comments Does anybody know why this doesn't work in Python 3?

When you put in 6 instead of max(arr) it works, but not if you put max(arr):

N = int(raw_input()) arr = map(int, raw_input().split()) print max([x for x in arr if x != 6])

^ works

ZNevzz + 1 comment I just thought to make the occurences of my most maximum the most minimum .

`t=int(input()) m=list(map(int,input().split(' '))) x=max(m) ind=list() for i in range(0,len(m)): if m[i]==x: m[i]=-101 print(max(m))`

karth2512 + 1 comment So Good !!! Can you please explain the "[:i]" in the end...? Is it to just accept the first i entries?

paul_schmeida + 0 comments It's called list slicing and returns a slice of the original list. The notation is [start_index:end_index:step]. Step defaults to 1. Both start_index and end_index can be omited, which will make them default to beggining and end of a list. Can be used with strings as well. You can use negative values to count from the end of a list (-1), as well as negative step to reverse the list.

amitiit + 0 comments But your list has been changed. so try something new, you can check my code. n=int(input()) L=(map(int,raw_input().strip().split(" "))) L.sort() a=max(L) b=L[0] for i in L: if i>b and i

narayanb345 + 0 comments there is no use of .strip() , you will get the output without that , if any please specify.Thanks

illumina_ova + 2 comments

Sort 3200 Discussions, By:

Please Login in order to post a comment