Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Fix second_largest so that it gives the second largest different value, and None when there is none. Test it with [5, 9, 2], [9, 9, 3], [5, 5, 5], [8] and [].
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Remove the repeats with a set, sort from the biggest, and check the length before you take position 1.
Check. [5, 9, 2] gives 5. [9, 9, 3] has the different values 9 and 3, so 3. [5, 5, 5] has one different value: None. [8] and []: None. No IndexError is possible, because the length is checked first.
Answer: 5, 3, None, None, None.
Log in to join the discussion.
Loading…