10

Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a list and find the score of the runner-up.

Input Format

The first line contains N. The second line contains an array of N integers each separated by a space.

I found this solution

n = int(input())

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

can someone explain me why we are using map function here ?

Also if someone can explain me this line :

nums = map(int, input().split())
SAJW
  • 235
  • 2
  • 10
arijit rakshit
  • 127
  • 1
  • 1
  • 6

19 Answers19

8

So we can take this line:

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

And break it down into a few subparts:

nums_in = input()
nums_split = nums_in.split()
nums = map(int, nums_split)

In order, nums_in will be the list of numbers read in as a string. For the input string "1 5 73 29", it will be:

nums_in = "1 5 73 29"

nums_split will then be the list of numbers split into a string for each number:

nums_split = ["1", "5", "73", "29"]

Now, the map function will call a function (int in this case) on each item in a list ("1", "5", "73", "29" in this case), and create a new list with the values that function returns. So, for this example:

nums = [1, 5, 73, 29]

The map function in Python 2 always returns a list, so in Python 3, we need to add one more step:

nums = list(map(int, nums_split))

Or, use one of my favorite Python structures in both, the list comprehension:

nums = [int(n) for n in nums_split]
2

The map() function applies a given to function to each item of an iterable and returns a list of the results. The returned value from map() (map object) then can be passed to functions like list() (to create a list), set() (to create a set) and so on.

Example 1: How map() works?

def calculateSquare(n):
    return n*n

numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)

# converting map object to set
numbersSquare = set(result)
print(numbersSquare)

When you run the program, the output will be:

<map object at 0x7f722da129e8>
{16, 1, 4, 9}

The map() function executes a specified function for each item in a iterable. The item is sent to the function as a parameter.

map(function, iterables) 

Map applies a function to all the items in an input_list.

Most of the times we want to pass all the list elements to a function one-by-one and then collect the output. For instance:

items = [1, 2, 3, 4, 5]
squared = []
for i in items:
    squared.append(i**2)

Map allows us to implement this in a much simpler and nicer way. Here you go:

items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))

map isn't particularly pythonic. I would recommend using list comprehensions instead:

map(f, iterable)

is basically equivalent to:

[f(x) for x in iterable]

map on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially do a Cartesian product with a list comprehension though:

[(a, b) for a in iterable_a for b in iterable_b]

The syntax is a little confusing -- that's basically equivalent to:

result = []
for a in iterable_a:
    for b in iterable_b:
        result.append((a, b))
1

Map is a very simple built-in function.

So it applies the function to every item in the iterable series i.e sequence

map(function, sequence)

So in your case nums = map(int, input().split()) input().split() returns a list. And for every item in that list, the function int is being applied.

That is syntactically equal to

ls = []
for item in items: # here items is the sequence returned by split
    res = int(item)
    ls.append(res)
# ls will be list that the map returns.

So all the items in your input that were separated by the split() function are mapped to int() function. So all the items are converted to int type.

Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34
1

The most pythonic way , used filter() to filter only the second max value from the list.

if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))

maxv = max(arr)
l = list(filter(lambda x: x != maxv,arr))
print(max(l))
Praneeth T T
  • 305
  • 3
  • 9
  • 2
    This doesn't answer the question at all. – Adam Dadvar Dec 28 '18 at 12:40
  • @Praneeth - Does lambda function takes the second maximum value that is before the max value? If you can please elaborate more on this line: `l = list(filter(lambda x: x != maxv,arr))` – Eugene_S May 20 '20 at 23:10
1

Here's my solution to the same problem using set() to remove the duplicates and sort() in reverse to find out the desired element. Hope it's the simplest way one can approach this problem.

if __name__ == '__main__':
    n = int(input())
    arr = map(int, input().split())

    x = set(arr)
    x = list(x)
    x.sort(reverse=True)
    print(x[1])
Timus
  • 10,974
  • 5
  • 14
  • 28
Rahul Bordoloi
  • 145
  • 3
  • 9
0

You can also do it in this manner. First, we should make sure that we don't have any duplicated so we are making a set out of the given values to remove duplicated and then sort them in descending order. Then we are printing the second highest value that is present at index 1 of the list.

if __name__ == '__main__':
    n = int(input())
    arr = map(int, input().split())
    arr_set = set(arr)
    arr_list = list(arr_set)
    arr_list.sort(reverse = True)
    print(arr_list[1])
Anirudh
  • 27
  • 1
  • 7
0
result = list(arr)
rem_val = []
max_v = max(result)
for i in result:
    if i < max_v:
    rem_val.append(i)
print(max(rem_val))

Blockquote From the instruction, you will need to cast your arr value as list, because your arr value appear as 3434543.

0

Below is my take at the solution:

if __name__ == '__main__':
    n = int(input()) # Declaring size of array eg: 5 <- 5 values
    arr = map(int, input().split()) # Values in array eg: 1 2 3 4 5
    
    scores = [x for x in arr] # Storing values of array in a list
    print(max([x for x in scores if x!= max(scores)]))

The idea is to create 2 lists:

  • List 1 includes all values of the input array.
  • List 2 excludes the maximum value from List 1 and I simply print out the maximum value from list 2.
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Lucas
  • 109
  • 5
  • 1
    Both `array` and `scores` is not necessary. Just do `scores = list(map(int, input().split()))`... – Tomerikoo Feb 17 '22 at 14:44
  • You are also repeatedly calling `max(scores)`. It would be simpler to call it once, outside the list comprehension and use that saved value... – Tomerikoo Feb 17 '22 at 14:50
0

I have solved this using sort and function and then we cat get before the maximum item that is the runner-up score.

if __name__ == '__main__':
  n = int(input())
  arr = map(int, input().split())

  list =[]
  for val in arr: 
    if val in list: 
     continue 
    else:
      list.append(val)
  sorted = sorted(list)
  print (sorted[-2])
-1

I solved it with this, ask me if you need me to explain!


n = int(input())
arr = sorted(list(map(int, input().split())))
max = -100
runner = -100
for i in arr:
    if i > max:
        runner = max
        max = i
print(runner)
FlipFloop
  • 1,233
  • 1
  • 14
  • 25
-1

I have prepared this program that is using Map function which will help you find the runner up scorer from the inserted list.

import heapq

n = int(input())

arr = []

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

arr = (list(set(number)))

m = sorted(set(arr))[-2]

arr.sort(reverse = True)
m = heapq.nlargest(2,arr)

print(m[1])

shadow
  • 1
  • 1
-1

I have solved this using sort function and then removed max entry, the number of times it is repeated using for loop, then printed the first entry from the last which, finds the runner up score from the list

n = int(input('enter the size of list:'))
arr = list(map(int, input('Enter entries with space:').split()))

arr.sort()
k = arr[0]
for i in arr:
    if i > k:
        k = i
for l in range(arr.count(k)):
    arr.remove(k)
print(arr[-1])
-1

I found this answer to be the simplest and the most effective so far.

  1. I turned the array into a list.
  2. Turned the list into a set, to avoid duplicate values.
  3. Then sorted the set.

ordered = sorted(set(list(arr)))

Lastly, just printed the ordered set and asked for the second last [-2] value.

print(ordered [-2])

raffi
  • 1
-1

The following is quite a non-pythonic way of writing the "Runner-Up Score!" code. It is beneficial for amateur coders who have just shifted from C/C++ to python3. It creates an additional list last (here) as most of us are not quite comfortable with the concept of maps in python. Hope you like it!

n = int(input())
arr = map(int, input().split())
lst=[]
for i in arr:
    lst.append(i)
lst.sort(reverse=True)
max=lst[0]
for i in range(len(lst)):
    if lst[i]==lst[i+1]:
        continue
    else:
        max=lst[i+1]
        break


print(max)
dippas
  • 58,591
  • 15
  • 114
  • 126
-1
A = []

n = int(input("Enter no. of Integers : "))

for  i in range(0, n):
    ele = int(input())
    A.append(ele)
print(A)
j = set(A)
j1 = list(j)
j1.sort(reverse=True)
print(j1)
print(j1[1]
deadshot
  • 8,881
  • 4
  • 20
  • 39
-1
def remove_duplicate(arr):
    li = [] 
    for n in arr: 
        if n not in li: 
            li.append(n) 
    return li
if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().split()))
    arr.sort()
    arr=remove_duplicate(arr)
    print(arr[-2])
ritish
  • 1
  • 1
-1
if __name__ == '__main__':
    n = int(input())
    arr = map(int, input().split())
    print(sorted(list(set(arr)))[-2])
Timus
  • 10,974
  • 5
  • 14
  • 28
tanmaychk
  • 37
  • 5
  • 2
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – wscourge Nov 30 '20 at 07:09
-2
if __name__ == '__main__':
n = int(input())

arr = map(int, input().split())
x=sorted(list(arr))
a=x[-1]
for i in range(len(x)):
    if x[i]==a:
        print(x[i-1])
        break
theyk
  • 224
  • 2
  • 4
-2

The objective is to find the second runner-up. To obtain the second runner-up we have to first sort the list in ascending manner and then get the second position for the list.

print(sorted(set(arr))[-2])
endo.anaconda
  • 2,449
  • 4
  • 29
  • 55
Iqbal
  • 1