-3

Task: Given n numbers, I store them in a list and find the second highest.

I found a solution by acisikta19 on Github:

    n = int(input())
    arr = list(map(int, input().split()))
    arr.sort()
    max1=arr[-1]
    arr.sort(reverse=True)
    for x in arr:
        if x!=max1:
            result = x
            print(result)
            break

I wanted to ask what max1=arr[-1] does? Particularly the -1?

Second, does arr.sort(reverse=True) simply sort the negative numbers? (The array of numbers is in [-100,100].

  • -1 is the last element of a list. -2 is the 2nd last element. When you add a negative sign to the number, you start to count backwards. Unlike elements starting from 0, the reverse starts from 1. so -1 is last element while 0 is the first element. If the array is a 2x2 matrix, then its row x col. whichever has a negative value you go from the back (bottom or right) – Joe Ferndz Jan 06 '21 at 03:27
  • Also that solution is weird at best. Try `sorted(arr)[-2]`, assuming the list has at least 2 numbers. Else, slice it first. – kwkt Jan 06 '21 at 03:38
  • @JoeFerndz, yes your explaination helps a lot! And just to clarify, would the backwards counting (say -2) give me the same result if I hadn't sort the number already? For example {1,-1,3,4} would the program return -1 or 1 if I didn't already sort the list?) – cheeseboardqueen Jan 06 '21 at 03:43
  • Hi @kwkt, I have not learned about the slice yet. I'm learning python on my own and just an embryo it seems :) – cheeseboardqueen Jan 06 '21 at 03:45
  • 1
    @cheeseboardqueen, the -1, -2, -3. .... does not refer to the value inside the list. Instead it is referring to the position of the element in the list. A few of the answers below explain it well. – Joe Ferndz Jan 06 '21 at 03:48

2 Answers2

2

Take the following array:

arr = [5, 1, 7, 3, 6, 9, 22, 66, 15, 68]

arr[0] will be 5, arr[1] will be 1, arr[2] will be 7, and so on.
arr[-1] will be 68, arr[-2] will be 15, arr[-3] will be 66, and so on. When you write arr[n] (where n is a number), python will take the nth element of arr (python counting doesnt start with 1, but with 0). When you write arr[-n], python will take the nth element of the back of arr (python reverse counting does start with 1).

TheEagle
  • 5,808
  • 3
  • 11
  • 39
1

I think it's best to Google around first:

This gets the element from the back of the list (think underflowing). -1 means the last element, -2 the second last, and so on.

This keyword sorts the list in descending order (instead of the default ascending order).

kwkt
  • 1,058
  • 3
  • 10
  • 19