1

I am attempting to solve the HackerRank problem, here: https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem

However, when I attempt the following code:

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

    maxVal = max(arr)
    print ("Max: ", maxVal)

    minVal = min(arr)
    print ("Min: ", minVal)

I get the output:

Max:  6

And the following error:

Traceback (most recent call last):
File "Solution.py", line 9, in <module>
minVal = min(arr)
ValueError: min() arg is an empty sequence

However, if I flip the rotation and find min first instead of max:

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

minVal = min(arr)
print ("Min: ", minVal)

maxVal = max(arr)
print ("Max: ", maxVal)

I get the output:

Min:  2

And the following error:

Traceback (most recent call last):
File "Solution.py", line 8, in <module>
maxVal = max(arr)
ValueError: max() arg is an empty sequence

This does not make any sense to me as to why it lets me find the max if I haven't already found the min, or it will let me find the min if I haven't already found the max.

If someone could explain this to me I'd greatly appreciate it.

Bradie
  • 45
  • 6

2 Answers2

2

Your iterator created by map is empty after calling min or max on it.

You can do:

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

    maxVal = max(arr)
    print ("Max: ", maxVal)

    minVal = min(arr)
    print ("Min: ", minVal)
ProteinGuy
  • 1,754
  • 2
  • 17
  • 33
1

The map function creates a generator, which can only be iterated through once. That's why the second time is raising an error. You should make arr a stable iterator, like a list.

schwartz721
  • 767
  • 7
  • 19