## Find the Runner-Up Score!

nnk94087 + 55 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 + 7 comments that's pretty elegant code!

Hassassin + 3 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 + 1 comment you do have a point, max() is O(n), it's not very efficient if there are many duplicated max values

- JA
jcdeargaez + 0 comments [deleted]

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

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

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

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

hyankov + 4 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 + 9 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 + 1 comment Oops, my bad - I missed you were using set prior sorting. Nevermind - it looks great!

- SE
santosheswaran + 4 comments 5

-7 -7 -7 -7 -6

for this input i think your code wont wholes good

- A
albert18 + 2 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)

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

KeyurPotdar + 1 comment 1 line.

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

salvadharani_84 + 0 comments [deleted]

- SS
bONSPARROW + 0 comments it works.

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

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

- VK
konidala_venky11 + 1 comment what if there is a repetition of the max number -2 wont work there

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

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

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

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

- SS
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 + 1 comment What would your code do for Input [2,2,2,2]

Divan_Cyph + 0 comments Use Try and Except

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

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

- OÃ–
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]

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

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

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

istewartbinks + 1 comment nlog(n) though.

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

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.

- AH
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]- PW
prachi_waghmare1 + 0 comments print(sorted(set(l))[-2]) this works

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

- SG
sankalpgupta13 + 0 comments n is nowhere to be used

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

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

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

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

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

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

- ML
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.

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

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

- MG
surfer2047 + 0 comments even without using list

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

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!

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

- SG
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.

- EP
eduardo_prz_gmz + 1 comment 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))

- JD
jae_duk_seo + 0 comments This is very interesing solution

- DG
mikee531 + 0 comments dude where are we using n here??

mazhuo79 + 0 comments This is a great solution.

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

Alpha__Wolf_ + 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]- AP
anany_boss + 0 comments you dont need to convert it into list! sorted(set(nums))[-2] works fine even with negative numbers

- AW
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 ?

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

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

just try it

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

MaxNRG + 0 comments make set :)

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

- B
balaji_m_2016_c1 + 0 comments [deleted]

- SC
IamSuRjya + 0 comments This wont work on Python 3.

- PF
pedroferreira_11 + 0 comments 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]

hapylestat + 0 comments not at all, quite unstable

sharq + 0 comments This code also works

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

- P
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 + 0 comments sort wont work because you are taking a string. try to use map and map int function on your list.

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.

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

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

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

- XY
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!

- TD
wuestenblume + 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)

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

- AD
Duboyal2 + 0 comments [deleted] - AJ
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.

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

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

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

- NS
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?

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

ZachPerkitny + 0 comments [deleted]ZachPerkitny + 0 comments [deleted]ZachPerkitny + 0 comments [deleted]- M
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()

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

- GC
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]??

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

- BS
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? - AJ
amoljoshi1993 + 0 comments What does [:i] do exactly???

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

- SF
samfelder17 + 0 comments why avoid set and sort?

- TA
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 + 0 comments 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))

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

- JP
jeffreypanghulan + 0 comments [deleted]

- TS
tanmaysankhe97 + 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)

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

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

while max(lis) == z:

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

codebloode_123 + 0 comments yes i used sort and set

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

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

- KD
keerthidurairaj + 0 comments elegant solution

rajat_yadav + 0 comments that's pretty good code

- MT
abedsarkil12 + 0 comments helpful

binit92 + 0 comments Isn't it calculating max in the list two times with complexity O(n) + O(n). It is possible to do it in one loop ..

if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) max = arr[0] runner = -9999 for score in arr[1:]: if score > max: runner = max max = score elif score < max and score > runner: runner = score print(runner)

vkuberan + 0 comments Very elagant piece of code....

danielsolisprado + 0 comments I did first part like yours, but then when creating the logic I was checking against if's. First it was ugly and then it failed with -10,0,10... Looking at your approach it very intelligent... getting the max, then deliting all the max's within the list, then looking for a new max.... awesome :D

- AS
mca2k6_jsr + 0 comments Can you please explain

lis = list(map(int,raw_input().strip().split()))[:i]? nayelhi_deanda + 0 comments Good code! Just, I do not have clear this part of the code:

.split()))[:i]

Could somebody explain it.

faizjaved + 1 comment new_arr = list(filter(max(arr).__ne__, arr)) print(max(new_arr))

- SC
saumitra13325 + 0 comments what is the

**ne**doing here?

mmehzad360 + 0 comments Can somebody explain me this line:

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

I've never used map(), So I have no idea about it :/ . Let alone map(), I need a clear explanation of the line.

touihri_rania + 1 comment Basically in one line :

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

EricDalrymple + 0 comments Word.

qingchen + 0 comments My solution:

if __name__ == '__main__': n = int(input()) arr = map(int, input().split()) print (sorted(set(arr))[-2])

'Set' is the key.

jasonganub + 2 comments Following all of the constraints of the problem statement, I was able to get all of the test cases to pass with this solution that avoids using the max() built in function and from modifying the original arr map list.

if __name__ == '__main__': n = int(input()) arr = map(int, input().split()) largest = -101 second_largest = -101 for i in arr: if i > largest: second_largest = largest largest = i elif i > second_largest and i != largest: second_largest = i print(second_largest)

emanweg + 1 comment Jason, I did something similar to yours but took the sorted function and used it to avoid the same pitfall I found tried doing your method (Having a pre defined veeeery low number. Have you thought about using - inf ?)

n = int(input()) arr = map(int, input().split()) arrSorted = sorted(list(arr)) index = 0 index_numero = 0 segundoNumero = arrSorted[0] while index < len(arrSorted): if arrSorted[index] > segundoNumero: segundoNumero = arrSorted[index] index_numero = index index += 1 else: index += 1 print(arrSorted[index_numero-1])

jasonganub + 0 comments Very nice. I like your way more of sorting it first. I would do largest = arrSorted[0] and second_largest = arrSorted[1]. I will use for future scenarios, thanks.

MaxNRG + 0 comments print(sorted(set(arr))[-2])

- AV
SandyElms + 3 comments print sorted(set(arr))[-2]

J___I + 0 comments My solution as well.

- V
v123582 + 1 comment print(sorted(list(set(arr)))[::-1][1])

- BB
bb5kb + 1 comment Can you explain the functionality of [::-1] used in your code? I figured it reverses the list order but could you expound on what the different ':' are for and '-1' is doing exactly to cause to flip the order?

- BH
codeharrier + 0 comments foo[i:j:k] gives a slice of list foo from i to j (but not including j) by step k

when i or j is omitted, it takes the whole range, so [::1] means "from first to last". but if k is negative, the order is reversed, so [::-1] means "from last to first"

it's a cute way of getting the list in reverse order, in other words

so then he uses the [1] index to get the second element in the reversed list, which gives the runner-up value

could just have used [-2] instead of forcing the list to be reversed

- CB
chadbrabec + 0 comments yep, same. except with python3 you need parents around what you want to print.

- MJ
horrorclause + 0 comments n = int(input()) arr = list(map(int, input().split())) new = [x for x in arr if x < max(arr)] print(max(new))

tbird234 + 0 comments if __name__ == '__main__': n = int(raw_input()) arr = map(int, raw_input().split()) myList = list(set(arr)) myList.sort() myList.pop() print myList.pop()

- KS
kirtivardhan80 + 0 comments if __name__ == '__main__': n = int(raw_input()) arr = map(int, raw_input().split()) lst = [] for i in arr: if i<max(arr): lst.append(i) print max(lst)

- SN
sasikanth_nagal1 + 1 comment `n = int(input()) arr = map(int, input().split()) print (sorted(set(arr),reverse=True)[1]);`

Ruth_15 + 0 comments anyone explain this ?

deimoss42 + 0 comments Just set it!

if __name__ == '__main__': n = int(input()) collection = set(map(int, input().split())) collection.remove(max(collection)) print(max(collection))

Sort 725 Discussions, By:

Please Login in order to post a comment