1

Im having trouble with this more advanced scenario.

I understand this:

def max(alist):
    if len(alist) == 1:
        return alist[0]
    else:
        m = max(alist[1:])
        return m if m > alist[0] else alist[0]

Which finds the max number in a list using just recursion. This repeats the function slowly shrinking the list every time which I get. My problem is I need to create a function that returns the 2nd smallest number. I dont understand how to do this since you need to compare each item with the rest of the items in the list. How would I do this with only recursion and no built in functions or for loops?

  • 1
    function names should stylistically be lower case ;) oh and you shouldn't override the built-in `list` function – Joe Iddon Jul 04 '18 at 21:33
  • I would recommend instead of making a function that handles the special case of `2nd` largest, take a look instead on finding the `kth` largest, which can give you the `2nd` largest through [pivoting](https://stackoverflow.com/questions/33625995/kth-smallest-element-in-an-array-using-partition), since your solution requires recursion. – Miket25 Jul 04 '18 at 21:36
  • Fixed the styling errors. I still have no idea how to start this second smallest function.I can only have one input which is the list if that matters. –  Jul 04 '18 at 22:00
  • Possible duplicate of [python 3.2 - find second smallest number in a list using recursion](https://stackoverflow.com/questions/28144569/python-3-2-find-second-smallest-number-in-a-list-using-recursion) – Radiodef Jul 05 '18 at 01:01

1 Answers1

0

I would sort it (merge sort), then take the second element, giving time complexity O(nlog(n)):

def second_max(lst):
    #takes two sorted lists and merges them together
    def merge(a,b):
        if len(a) == 0: return b
        if a[0] < b[0]:
            return [a[0]] + merge(a[1:],b)
        else:
            return [b[0]] + merge(b[1:],a)
    #breaks list down and then merges back up - sorting
    def merge_sort(lst):
        if len(lst) == 1: return lst
        h = int(len(lst)/2)
        return merge(merge_sort(lst[:h]), merge_sort(lst[h:]))
    #return second element from sorted list
    return merge_sort(lst)[1]

and a test:

>>> second_max([9, 3, 9, 6, 2, 4])
3
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54