Won Kim
Won Kim

Reputation: 109

Returning the second largest in the list

def second_largest(nums):
    the, sec = 0, 0
    if nums[0] > nums[1]:
        the, sec = nums[0], nums[1]
    else:
        the, sec = nums[1], nums[0]

    for num in nums:
        if num > sec:
            if num >= the:
                the, sec = num, the
            else:
                sec = num
    return sec

This is my code to get second largest element from the list. I assumed that a list has at least two elements. However, it gives me 'gamma' not 'delta' from the input below.

print(second_largest(['alpha', 'gamma','beta','delta']))

Upvotes: 2

Views: 110

Answers (2)

pd shah
pd shah

Reputation: 1406

a simple way is to find max and remove it. finding the max is on o(n)

>>> x=['alpha', 'gamma','beta','delta']
>>> m=x[0]
>>> for i in x:
    if i > m:
        m=i

>>> x.remove(m)

and for second time:

>>> m=x[0]
>>> for i in x:
    if i > m:
        m=i
>>> print(m) #scond max

o(n)+...+o(n) -> L * o(n) -> o(n)

Upvotes: 0

Ry-
Ry-

Reputation: 224887

You've initialized the largest and second-largest values to the first two items in the appropriate order, but then you're including them again in the loop. If the largest value was also one of the first two values, it will take up both slots after that point. You can fix it by creating an iterator from the list explicitly and advancing it for the first two elements:

def second_largest(nums):
    it = iter(nums)
    sec, the = sorted((next(it), next(it)))

    for num in it:
        if num > sec:
            if num >= the:
                the, sec = num, the
            else:
                sec = num

    return sec

By not using indexed access, this also has the advantage of working on any iterable.

For real-world use, see heapq.nlargest, which even has specific optimizations in CPython for small numbers of elements.

Upvotes: 6

Related Questions