We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

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)

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

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

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

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?

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

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

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)

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

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)

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?

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

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.

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

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.

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

deffunc_maximo():maximo=Lista[0]forzinrange(len(Lista)):ifLista[z]>maximo:maximo=Lista[z]returnmaximoif__name__=='__main__':#Declarnado Variaveln=int(input())arr=map(int,input().split())# Tudo em ListaLista=[]forxinarr:Lista.append(x)# Maior Numerox=func_maximo()# Removendo o maior numerowhilefunc_maximo()==x:Lista.remove(x)# Printando o segundo maior numero apos removerprint(func_maximo())

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)

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.

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.

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

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.

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

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!

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?

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

n = int(raw_input())
arr = map(int, raw_input().split())
dup =[]
for i in arr:
if i not in dup:
dup.append(i)
dup = sorted(dup)
print dup[len(dup) - 2]

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.

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

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.

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.

No. I made the max value in the list the min value by updating it to -101(see the constraints). So the 2nd max value automatically becomes the max value

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.

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

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

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

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?

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)

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.

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

arr=map(int,raw_input().split())arr.sort()print"elelments are %r"%arrm=max(arr)print"maximum number is %r "%ml=len(arr)print" length of the list is % r:"%lforiinrange(0,l):ifarr[i]==m:print"%r is equal to %r"%(arr[i],m)delarr[i]printmax(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.

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

Bit of a simple question I was also trying to use remove(max(array)). Please could someone explain why
highest = max(array)
while max(array) == highest:
array.remove(max(array))
print(max(array))

works but this won't:
array.remove(max(array))
print(max(array))

Am I wrong that this solution is > O(n)? This problem can be done in linear time, no? Python's max() is O(n) and you call it twice each iteration and only luckily reduce n by 1 each iteration. The set [2,2,2,2,2] would have like 30 comparisons to find max plus 5 for your z initialization and then 0 for the print I believe. 5+5+4+4+3+3+2+2+1+1+0+0
[1,2] would be 2+2+1
[1,7,3] would be 3+3+2

we go to the 3rd line
m=max(arr) #we put the maximum value of the array in the varriable m

while m in arr : #loop the array looking for the maximum value
arr.remove(m) #remove that maximum value
#repeat the loop until ther's no value equale to the old maximum value so ther's only the secon maximum who becom the maximum value
print(max(arr)) #the we print the actual max (the second )

## Find the Runner-Up Score!

You are viewing a single comment's thread. Return to all comments →

I was trying to avoid set and sort, came up with this

that's pretty elegant code!

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)

reduce(lambda x,y: x if x>y else y, nums)

returns max element in nums list!

Check this link for more info

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

@tao_zhang, here it is for many duplicated max values -

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

max and remove both are O(n)

Great solution. You could also do away with the

'i'variable and thewhile loopby replacing them with afor loop.edit: fixed logical error

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

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

ok good kuck

he figured out that

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

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

## your error wont occurs here

if

name== 'main':hey I am new to python here.can u tell me what is significance of map keyword while taking inputs.

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

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

yes!!one more point!!

it wont work for multiple max value...

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?

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

yes, thats why you should try this

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

Amazing!! Simplicity at its best

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.

nusta indentation error...

very nice code . Thanks

can you pls explain why -1,-1,-1 ??

thats nothing just for counting the nums from reverse...

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

could u elaborate the 4th and 5th line?

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

Thanks for this! Very clear

## use it

if

name== 'main':Simple and super

can u please explain it to me

**

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

Thanks

Great!!

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)

Why are we using not in?

**

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

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)

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?

can anyone please explain this code

**

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

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.

why did you add list here?

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

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

@DeerFace, good tip! cheers!

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

the line 6 is error

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

I am also getting same error. however its res==max(arr)

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.

can u plz keep the snippet of ur code?

can anyone explain this code

use set instead of list

Thank u for your solution...It is very helpful for python beginner like me

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

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

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

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

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

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

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

I am trying same.

How about this shorter one...

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.

You can try it! :)

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.

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

5

-7 -7 -7 -7 -6

for this input i think your code wont wholes good

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)

His code works. You should try it again dude

Works in python 2 only

It still works. I just checked.

it works.

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

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

I mean 3 numbers: [5, 5, 5]

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])what [-2] does please explain.

Refers to the second to last element.

what if there is a repetition of the max number -2 wont work there

code uses a set(only distinct numbers)

Set can have only non-repeating values

Set can have only non-repeating values

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

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

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

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

-ve index signifies starting from last index

I think you don't need sorted, works just fine without it.

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.

What would your code do for Input [2,2,2,2]

Use Try and Except

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

set does not consist of indices

moglobal thats one of the best code ive ever seen.. great job!!!

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

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

pretty cool. thanks for sharing. I had the same intent but missed the set/duplicate part.

Why do we need "list" here?

Correct bro,Set is able to store only non-duplicate....

Very nice, learn something new everyday, very pythonic :)

thnq

Not Working for me!

I think its correct as set will remove duplicate values

but set would return unique elements i guess

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

he use set datatype

nlog(n) though.

no,BFPRT,O(n)

try this @R)Try&i

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

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

I did a similar thing:

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

print(sorted(set(l))[-2]) this works

Just myList[-2] - is shorter and still correct.

hi can you tell me please where the value of n is being used and how ? thanks any ways

n is nowhere to be used

Can you please tell what map() is doing here ?

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

List isn't necessary as sorted takes any object iirc

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

Thank you so much.. superGogeta

Thanks & Regards

Camel casing my name lol, Your welcome :)

Nice. My code is same as yours except you handled unnecessary

`n`

input in one line :)I was able to do it in one line. But I will not tell you how! Try to figure it out yourself HA HA

Can anyone plz explain why sorted() works and not the function sort() ?

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.

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

:'set' object has no attribute 'sort'

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

won't work if 6,6 element are the largest in list

thanks it worked for me.

even without using list

can you explain [-2]

seond from the end

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!

Good one moglobal!

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

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

It returns list with unique values.

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

This is very interesing solution

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!

Nice! Here's an even shorter version using your approach:

dude where are we using n here??

Actually 'n' is used here to iterate 'arr' object

and

are same

Hope this helps!

This is a great solution.

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

It is wonderful broo

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]

you dont need to convert it into list! sorted(set(nums))[-2] works fine even with negative numbers

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?

Python 3 version:

what if i want to print the max no as well as second max no ?

you can use:

just try it

what does the function set()do?

make set :)

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

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

wow that was smooth... why i didnt think that way... lol i always choose long path

Good answer. It can be done without casting to a list:

Although I don't see why you had to apply

`list`

to the`set`

.May be a noob version of your code

It worked, Thanks

that's cool dude

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

Really awesome logic.

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

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]

I like this solution

This wont work on Python 3.

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]

I don't understand at all.

not at all, quite unstable

This code also works

nothing So beautiful

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

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

Can you pls explain how this works??

Its working for negative numbers.check this

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

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

@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. " "

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.

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

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

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

You don't need that tmp var, just reorder your first condition:

works!but a little improvement is needed

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

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

inside the loop.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)])

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

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.

Thanks for the clear and concise comparison!

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.

I did mine similarly, but with filter.

This wont work in python 3 , but works in python 2

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

^ works

I just thought to make the occurences of my most maximum the most minimum .

But how about -101 is the max value in the list?

No. I made the max value in the list the min value by updating it to -101(see the constraints). So the 2nd max value automatically becomes the max value

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

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.

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

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

As for me, no function at all except list initialization.

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

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

Even my apporach was this :D

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}).Max is O(n), where n is the size of the list. https://wiki.python.org/moin/TimeComplexity

This is O(n^2) altogether.

brilliant

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

In Python 3, map() returns a map object.

Can you explain why you did max(lis) == z in the while list?

py3 in one line :)

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

Brilliant!

Nice think of code man.

I think it doesn't need to use strip()

ur code will not work if all the no in the list is same

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?

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

What actually this statement does? Can anyone please clarify

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

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

hey,why that extra split()[:i]??

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

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 withmap()? Also, why the[:i]at the end?What does [:i] do exactly???

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)

why avoid set and sort?

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.

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

Thats my code and I am really not proud of that :/

I add set to remove duplicate maximum element

Genius!

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.

I did kind of same

using filter..

What is the purpose of the line:

An optimal method without set. Nice!

yes i used sort and set

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

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

elegant solution

that's pretty good code

helpful

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

Very elagant piece of code....

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

Can you please explain

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

Good code! Just, I do not have clear this part of the code:

Could somebody explain it.

what is the

nedoing here?Can somebody explain me this line:

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

You have an error in code, at least in Python3 version.

print max(lis) is wrong syntax, instead of it you should do print(max(lis))

Otherwise, all great! Cheers!

Bit of a simple question I was also trying to use remove(max(array)). Please could someone explain why

`highest = max(array)`

while max(array) == highest:

array.remove(max(array))

print(max(array))

works but this won't:

`array.remove(max(array))`

print(max(array))

Can anyone please tell me if map() returns a list itself then why do we have to typecast it using into a list as done in lis =

list(map(......))Great!

Pretty confused. I did pretty much exactly what you were trying to do

import operator

if

name== 'main': n = int(raw_input()) arr = map(int, raw_input().split()) max_value = max(arr) arr = arr.remove(max_value) second_max = max(arr)but I get a runtime error with this code.

adding strip was not really necessairy since max work with iterables

Am I wrong that this solution is > O(n)? This problem can be done in linear time, no? Python's max() is O(n) and you call it twice each iteration and only luckily reduce n by 1 each iteration. The set [2,2,2,2,2] would have like 30 comparisons to find max plus 5 for your z initialization and then 0 for the print I believe. 5+5+4+4+3+3+2+2+1+1+0+0 [1,2] would be 2+2+1 [1,7,3] would be 3+3+2

I s this a problem of data structure?

can you please explain me this code?

ofc , so the 3 first line are generic

we go to the 3rd line m=max(arr) #we put the maximum value of the array in the varriable m

How about 2 iteration over the array. First to find the maximum ele. Second to find the second max ele.

a pleasure to see your code froma beginner level coder perspective!!

using list comprehension:

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

wouldn't it have a time complexity of O(n^2)?

print(sorted(set(map(int,input().split())))[-2])

fool

get lost