Find the second smallest number in a list using recursion

后端 未结 6 1973
故里飘歌
故里飘歌 2021-02-19 18:08

I know there has been a question asked on this topic, but none of the answers have helped me. I don\'t need help with implementing the code, I just need help sorting through the

6条回答
  •  囚心锁ツ
    2021-02-19 18:34

    What I understand from question :- 1. Solution should be recursive 2. No inner function kind of hack 3. It should return second smallest and accept list as parameter My Code to solve this -

    from inspect import getouterframes, currentframe
    def second_smallest(ls):
        level = len(getouterframes(currentframe(1)))
    
        if len(ls)<2:
            return None
        if len(ls) == 2:
                    if level == 1:
                        return max(ls)
                    else:
                        return min(ls), max(ls)
        else:
            m,n = second_smallest(ls[1:])
            if ls[0]<=m:
                n = m
                m = ls[0]
            elif ls[0] < n:
                n = ls[0]
            if level == 1:
                return n
            return m,n
    

    Note - This code works if you run as python program file

提交回复
热议问题