Python3: Find the n-th largest number in a sequence

Words
17
Reading
1 min
Listen
Play
4y

TASK: Find the n-th largest number in a sequence without sorting and without modify the original sequence.

original: list[int] = [3,7,-13,6,9,-6,13,45,33,-2,2,5,12]


def nth_largest_number(nth: int):

    # in case n is greater then the length of the list
    if nth > len(original):
        print('n greater than length of list')
        return

    # copy the original list because we are not allowed to modify the original
    temp: list[int] = original.copy()

    # find the n-th largest number
    for run in range(nth):
        maximum: int = -sys.maxsize
        for elem in temp:
            if maximum < elem:
                maximum = elem

        # remove the largest number from the copied sequence and rerun the loop
        temp.remove(maximum)
    print(nth,'th-largest number is',maximum)


if __name__ == '__main__':
    nth_largest_number(1) #run 1
    nth_largest_number(3) #run 2
    nth_largest_number(11) #run 3
    nth_largest_number(14) #run 4, expected error

Python3: Find the n-th largest number in a sequence | Ecency