0

List of items are there as a map object. I have to iterate this 2 times to get an answer. Is this possible without converting into a list?

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

    large = 0
    for item in arr:
        if item > large:
            large = item
    print(large)

    second = 0
    for item in arr:
        if item < large and item > second:
            second = item
    print(second)

Expected result for an input of "2 3 4 6 6" is 6 4

Result from the above code is 6 0

3 Answers3

1

This code replicates behavior of your code in single loop.

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

    large = 0
    second = 0
    for item in arr:
        print('%s %s %s %s %s' %(item, large, second, item < large, item > second))
        if item > large:
            second = large
            large = item
        elif item < large and item > second:
            second = item
    print(large)
    print(second)
Radosław Cybulski
  • 2,952
  • 10
  • 21
0

From the documentation of map: Return an iterator that applies function to every item of iterable, yielding the results. Iterators are one-way, there's another question about "resetting" iterators, top answer is explaining why it may be a bad idea.

As you're using input(), not a file, it won't be possible to recreate the iterator the same way, so the best way is to make a list.

However, looking at your code, you will be able to do the thing in one pass. ;) - I won't post code as it looks like a coding exercise, only explanation how to do that: use two variables (or a 2-element tuple or 2-element list) during the first run already. New number is bigger than both? Change both values. New number is between them? Change only 2nd.

h4z3
  • 5,265
  • 1
  • 15
  • 29
0

We can iterate through single loop and we need to assume max and second max as first element than 0 because elements in array can be negative also

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

    large = arr[0]
    second_large = arr[0] 

    for item in arr:
        if item > large:
            large = item
        if item < second_large:
            second_large = item
    print(large, second_large)
MBT
  • 21,733
  • 19
  • 84
  • 102
  • map object cannot be called with indexes.. correct me if i am wrong.. large = arr[0] will throw an error.. – Parthiban Bala Jun 17 '19 at 15:06
  • arr contains array , map returns an array so you can access a[0] – krishna3442 Jun 17 '19 at 16:01
  • arr contains array , map returns an array so you can access a[0]. We use map function so that we can apply apply function to every element in an array. Here input().split() returns an array of strings and we are converting every element in array to integer so that we can find first and second maximum. – krishna3442 Jun 17 '19 at 16:13