# Find the Runner-Up Score!

# Find the Runner-Up Score!

nnk94087 + 111 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 + 7 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 + 0 comments reduce(lambda x,y: x if x>y else y, nums)

returns max element in nums list!

tao_zhang + 6 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 + 20 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 + 0 comments Use a set to get O(1) complexity.

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

arka_debojit91 + 0 comments Can you share the fixed code?

sjayanthkumar191 + 0 comments he figured out that

enji_py + 6 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 + 11 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 + 1 comment 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!!

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 + 0 comments 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.

swapnaj_nandgao1 + 0 comments nusta indentation error...

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

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

IndexError: list index out of range

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

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

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 + 0 comments no need to find largest number n=int(input()) l1=list(map((int),input().split())) l2=sorted(list(set(l1))) print(l2[-2])

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

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 + 4 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 + 5 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!!

abhi_moudgil15 + 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.

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?

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 + 0 comments 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.

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 + 0 comments the line 6 is error

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

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

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

friction560 + 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 """

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 + 0 comments Works in python 2 only

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 + 1 comment 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 + 1 comment 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

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 As for me, no function at all except list initialization.

`N = int(input()) a = list(map(int,raw_input().split())) max1 = max2 = -100 for i in a: if i > max1: max1 = i; i in a: if i > max2 and i != max1: max2 = i; print max2`

metoinside + 0 comments i in a: line trows an error but you give me the inspiration to implement your approach and I succeed :))

hamichok11 + 1 comment lol i did same, I'm a total noob, here's my solution:

if __name__ == '__main__': n = int(raw_input()) arr = map(int, raw_input().split()) largest=0 for num in arr: if num > largest: largest = num found=0 for num in arr: if num > found and num < largest: found = num print found

atchyutn + 0 comments Even my apporach was this :D

amazinghacker + 0 comments This has very poor time complexity...bcoz you check for max every time and you also use remove which has O(n) time. Hence your code is atleast O(n

^{2}).istewartbinks + 0 comments Max is O(n), where n is the size of the list. https://wiki.python.org/moin/TimeComplexity

This is O(n^2) altogether.

niwot + 0 comments brilliant

nanka_bananka + 1 comment Could you pls explain for what reason you used function 'list'? As I know, "map" is already returning list object. Am I wrong?

aaafarmclub + 0 comments In Python 3, map() returns a map object.

ZachPerkitny + 0 comments [deleted]ZachPerkitny + 0 comments [deleted]ZachPerkitny + 0 comments [deleted]msambitkumar1991 + 0 comments Can you explain why you did max(lis) == z in the while list?

Max_Vignesh + 0 comments Nice think of code man.

temari206 + 0 comments I think it doesn't need to use strip()

Pritam0209 + 1 comment ur code will not work if all the no in the list is same

temari206 + 0 comments strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string, right? But lis = list(map(int, raw_input().split()))[:i] is OK, the code still works well, because we have split(). Did u try it?

shibaprasad46 + 0 comments lis = list(map(int,raw_input().strip().split()))[:i]

What actually this statement does? Can anyone please clarify

giri_ch + 0 comments Can you please elaborate on the [:i] part in 2nd line?

liukrimhim + 0 comments You assumed that the max value does not have a duplicate. What if there are more than one max?

richacodes + 0 comments hey,why that extra split()[:i]??

jialuwei0811 + 0 comments Hi, Would you explain what is [:i] at the end of second line? thank you!

benyscott + 0 comments I had pretty much the same code as you but mine didn't work, I think it is because I didn't declare the list properly.

So, my only questions are about line 2. I had only used

**input().split()**and it seemed to work everywhere, except in tests #6, #9 or whatever.Is it needed to build a list with

**list()**, specify that the values are integers with**map()**? Also, why the**[:i]**at the end?amoljoshi1993 + 0 comments What does [:i] do exactly???

04neha + 0 comments The code seems better than what i tried but there is no check for validating the input taken in lis. That is it must be in between -100 and 100(given in constraints)

samfelder17 + 0 comments why avoid set and sort?

tabdikeeva + 0 comments Your function will return second value even if there is none. For example in you are looking for second largest in the list [5,5,5] there is no second largest value.

ACorran + 0 comments Mine (in python3)was same idea though a bit longer: n = int(input()) arr = input().split() m1 = max(arr) arr.remove(m1) m2 = max(arr) while m1 == m2: arr.remove(m2) m2 = max(arr) print(max(arr))

PkkdGuy + 0 comments Thats my code and I am really not proud of that :/

if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) rev_arr = sorted(arr, reverse = True) for i in range(n): if rev_arr[i+1]<rev_arr[i]: print (rev_arr[i+1]) break else: pass

saifulcseng + 1 comment I add set to remove duplicate maximum element

N=int(input()) s=list(set(map(int , input().split(' ')))) s.remove(max(s)) print(max(s))

lucas_ribeiropr1 + 0 comments Genius!

iamphanisai + 0 comments arr = map(int, raw_input().split()) arr.sort() print "elelments are %r"%arr m=max(arr) print "maximum number is %r " %m l = len(arr) print" length of the list is % r:" %l for i in range(0,l): if arr[i]==m: print"%r is equal to %r"%(arr[i],m) del arr[i] print max(arr)

PLEASE HELP! Why doesnt this get past all the test cases? It runs fine if the input is 1,2,3,4 or 4 3 2 1 or 4 4 3 1..but not the test cases.

jchimien + 1 comment `n = int(input()) arr = list(map(int, input().split())) largestNum = max(arr) while largestNum in arr: arr.remove(largestNum) print(max(arr))`

jeffreypanghulan + 0 comments [deleted]

tanmaysankhe + 0 comments I did kind of same

if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) mx = max(arr) while(mx in arr): arr.remove(mx) mx = max(arr) print(mx)

mail2karthk07 + 0 comments using filter..

n = int(input()) nums = list(map(int, input().strip().split())) z = max(nums) print(max(list(filter(lambda a: a != z, nums))))

kalesaur + 0 comments What is the purpose of the line:

while max(lis) == z:

sudhanshussr806 + 0 comments An optimal method without set. Nice!

codebloode_123 + 0 comments yes i used sort and set

ledestin91 + 0 comments anyone can explain why he put '[:i]' at the last part of second line? i have tired his codes without that thing, counldnt find any problem

miniamc + 0 comments Using list comprehension also works well, but I'm not sure about the efficiency!

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

keerthidurairaj + 0 comments elegant solution

rajat_yadav + 0 comments that's pretty good code

abedsarkil12 + 0 comments

Sort 2318 Discussions, By:

Please Login in order to post a comment