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)

Since Python's set abstract type is implemented as a hash table, construction of a set of n items is best case (i.e. low load factor) O(n). Therefore first constructing a set then finding its maximum is still O(n).

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

What does [-2] mean? I'm new here so I don't understand the use of print(arr[-2]). What does arr=sorted(list(set(arr))) actually do?
I would really appreciate your help.

You just need to search list sclicing properties and you will get the idea. Also arr=sorted will give you the sorted array from higest to lowest value. so that you can remeove the first element and print the second one which is the runner-up or second-higest.

2 test case are failing here and they might be when the array is empty and when all the elements are same. All over it's a one line question any way great approach.

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)

i have a doubt here, we are taking the value for n from user. If in this code I am starting to put value, I can put 5 for n , but I can do 10 or 20 values for arr
can you update where you can add only n elements taken from the user?

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.

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

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

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

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

n = int(input())
arr = list(map(int, input().split()))
negatives = [-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
d = []
for i in arr:
if i in negatives:
d.append(i)
d.sort()
d.reverse()
c = []
for i in arr:
if i not in c:
c.append(i)
c.sort()
print(c[-2])
*

## Find the Runner-Up Score!

You are viewing a single comment's thread. Return to all 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)

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

returns max element in nums list!

Check this link for more info

here is the solution of problem

find the runner up scorehttps://solution.programmingoneonone.com/2020/06/hackerrank-find-runner-up-problem-solution-python.htmlyou 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)

Use a set to get O(1) complexity.

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

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

In array/list, it could be but, in the above code the list has been converted to set. Set doesn't have same value multiple times.

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

could you please explain why you take y -9999? i cant understand you logic

To remove duplicates this function will help you:

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

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

it should be [-1]

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

it will become wrong if there are two same elements in list!

noob

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

What does [-2] mean? I'm new here so I don't understand the use of print(arr[-2]). What does arr=sorted(list(set(arr))) actually do? I would really appreciate your help.

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

You just need to search list sclicing properties and you will get the idea. Also arr=sorted will give you the sorted array from higest to lowest value. so that you can remeove the first element and print the second one which is the runner-up or second-higest.

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

this is coz, your code still consists of duplicate elements.First remove duplicate elements using

setand then print your result2 test case are failing here and they might be when the array is empty and when all the elements are same. All over it's a one line question any way great approach.

in this case you can use set <-list

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

Can you share the fixed code?

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

Not to be picky, but for

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

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

yields an iterable of the first ten perfect squares.Thanks ! Was very helpful

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

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

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.

Try this:

thanks for guiding me. :)

what does [-2] do ?

prints last but one element in array

nusta indentation error...

This code will fail if largest number occures multiple time.

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

List with same numbers wont have second largest number.

goog job ! really helpful , Danke schön...

thnaks bro good job

haha if name='main' good luck

Nice Logic

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

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

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

print(max(c))

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

Do you need to wrap set to list?

`arr = sorted(set(arr))`

should work.

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

solve this please for me:

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

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

try anyone who is intersted

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

could u elaborate the 4th and 5th line?

def y(x): return set(x)

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

whats wrong

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

solve this please for me:

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

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

try anyone who is intersted

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

use set instaed of list

hy could you explain itration of for loop kindly

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)

great help

this is called perfect lecture with handson.

solve this please for me:

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

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

try anyone who is intersted

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

i have a doubt here, we are taking the value for

`n`

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

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

can you update where you can add only`n`

elements taken from the user?perfect

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)

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

he eliminating the duplicacy, so his code works. he wrote very simple and proper code.

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?

solve this please for me:

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

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

try anyone who is intersted

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

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.

solve this please for me:

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

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

try anyone who is intersted

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

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

@DeerFace I am not getting the second line, can you please explain?

the line 6 is error

Same to my bro

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

Your cont won't work on input of 0 0 0 0 0

You would need to add below condition

in this case it dosent need

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

Hmm i am beginner but i wrote code in 6 lines

Could you not turn the list into a set to deal with multiple values?

Can u pls explain why did u used list here

I just Loved the logic that u have used.

thanks

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

if

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

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

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.

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

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

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

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

*