0
def thirdMax(nums):

    highest = max(nums)

    for i in nums:
        if i == highest:
            nums.remove(i)
    print(nums)

    secondHighest = max(nums)

    for i in nums:
        if i == secondHighest:
            nums.remove(i)

    thirdHighest = max(nums)

    return thirdHighest

thirdMax([1,2,3,3,3,3,3,3,4,4,4,4,4,4,4])

My code is supposed to return the third highest distinct number. My code isn't seeming to work accordingly.

SiHa
  • 7,830
  • 13
  • 34
  • 43
Raunak Anand
  • 47
  • 1
  • 2
  • 8

1 Answers1

0

Sort the list (to make sure). Convert to a set. Convert back to a list and take the 3rd from the right.

l = [1,2,3,3,3,3,3,3,4,4,4,4,4,4,4]
l.sort()
s = set(l)
l = list(s)
third = l[-3]

You can combine some of these steps, but I wrote them all out for clarity :)

michjnich
  • 2,796
  • 3
  • 15
  • 31
  • Oh that's a much easier way to go about it. But why wasn't my iteration removal method working? – Raunak Anand Oct 26 '19 at 20:06
  • Because remove only removed the first instance of the value it finds. In your case the 2 removed will reach remove a 4, leaving 4 as the highest number still. – michjnich Oct 26 '19 at 20:15