Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the second smallest number in a list using recursion

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 recursive process for this.

I was originally thinking recursively return a tuple each level and compare to find the second smallest value. But this doesn't work as I want my function to only return 1 value in the end- the 2nd smallest value.

How would I go about the recursive process for this problem? Thank you!

Edit: Sorry about not including enough details, so here goes.

Function should work as follows:

>>> sm([1,3,2,1,3,2])
>>> 2

Second edit: Sorry for the delay, I was busy until now, finally was able to sit down and put what I had in mind into code. It works as intended, but I honestly think this is a very shitty and inefficient way of doing recursion, as you can probably tell I am new to the concept.

To rephrase my original question using the pseudo code below: Is it possible to do what I did here, but without wrapping it in a second function? That is, is it possible to have a function that only recursively calls its self, and returns 1 number- the second smallest number?

def second_smallest(list):
    def sm(list):
        if base case(len of list == 2):
            return ordered list [2nd smallest, smallest]
        else:
            *recursive call here*
            compare list[0] with returned ordered list
            eg: [3, [5,2]]
            re-arrange, and return a new ordered list
            [3,2]
    return sm(list)[0]
like image 708
Nick Avatar asked Feb 09 '16 00:02

Nick


People also ask

How do you find the second smallest element in a list?

We can find largest and smallest element of list using max and min method after getting min and max element pop outs the elements from list and again use min and max element to get the second largest and second smallest element.

How do I find the second smallest item in a list Python?

First, we need to use the min() function to get the minimum value of the list. Then we use the list remove() function to remove the minimum value. We can then use the min() function again to get the second smallest number.

How do you find the smallest number in an array using recursion?

For finding Minimum Take array Arr[] as input. Function recforMin(int arr[], int len) takes input array and its length and returns minimum in the array using recursion. If the current index len is 1 then set minimum=arr[0] and return minimum. Else set minimum = minimum of arr[len] or recforMin(arr,len-1) and return it.

How do you find the second smallest number in an array C++?

Method 1 : Declare a variable say smallest = arr[0], that variable hold the first minimum value of the array. Run a loop and check if(arr[i]<smallest) then set smallest = arr[i]. Now, take a variable say sec_smallest = INT_MAX. Now, run a loop over the array, and check.

How to find second smallest number in a list using for loop?

Here are the list of programs: The question is, write a Python program to find second smallest number in a list using for loop. Here is its answer: Here is its sample run: Now supply any 10 elements or numbers for the list say 4, 5, 6, 2, 1, 0, 3, 7, 8, 9 and press ENTER key to find and print the second smallest number from the list:

How to find smallest and second smallest element in an array?

Find the smallest and second smallest elements in an array. Write an efficient C program to find smallest and second smallest element in an array. Example: Input: arr[] = {12, 13, 1, 10, 34, 1} Output: The smallest element is 1 and second Smallest element is 10. A Simple Solution is to sort the array in increasing order.

How to find the minimum size of an array using recursively?

Recursively find the minimum according to the following: Recursively traverse the array from the end. Base case: If the remaining array is of length 1, return the only present element i.e. arr [0] if (n == 1) return arr [0]; Recursive call: If the base case is not met, then call the function by passing the array of one size less from the end, i.e.

How to recursively call a function from a variable with smaller value?

We keep checking if num [n] is smaller than value present at variable small. If true, then we transfer num [n] value to variable small, and then recursively call the same function by decrementing the value of n by 1, and also pass the new value of small.


2 Answers

You can write your recursive function to take 3 arguments: the first and second smallest values you've encountered so far, and the rest of the list, which you haven't inspected.

Then, by comparing the first element of the list argument with the two smallest-so-far, you can choose which 2 of the 3 to pass as the arguments to the next recursion.

You need to wrap this recursive function in a presentation function, which sets up and calls the recursive one, while handling cases like lists that have less than 2 elements.

def recurse(min1, min2, list):
    if len(list)==0:
        return min2
    first, rest = list[0], list[1:]
    if first < min1:
        return recurse(first, min1, rest)
    if first < min2:
        return recurse(min1, first, rest)
    return recurse(min1, min2, rest)

def second_smallest(list):
    if len(list) < 2:
        raise ValueError("too few elements to find second_smallest")
    a, b, rest = list[0], list[1], list[2:]
    if b < a:
        return recurse(b, a, rest)
    else:
        return recurse(a, b, rest)

This kind of solution isn't particularly Pythonic -- it's more of a functional programming style.

Finally, you can pass the arguments on the front of the list, and combine the two functions to get the kind of solution you're looking for:

def second_smallest(list):
    if len(list) < 2:
        raise ValueError("too few elements to find second_smallest")
    a, b = list[0], list[1]
    a, b = min(a,b), max(a,b)
    if len(list) == 2:
        return b
    c, rest = list[2], list[3:]
    if c < a:
        return second_smallest([c,a]+rest)
    if c < b:
        return second_smallest([a,c]+rest)
    return second_smallest([a,b]+rest)

Note that this function does some redundant work, because it can't know if it's being called first, or if it's calling itself recursively. Also, + creates a new list, so this code will likely take O(n^2) time for a list of size n.

like image 136
comingstorm Avatar answered Oct 02 '22 19:10

comingstorm


You can use a flag to keep track whether you're in the most outer level of the calls.

def second_smallest(numbers, top_level=True):
    # Do your stuff and call `second_smallest(numbers[1:], False)` for any recursions.
    # When it comes to returning a value from the function, use the following.

    if top_level:
        return result[0]   # what your function ultimately returns
    return result          # [second, first] since you're still in recursive calls
like image 41
Reti43 Avatar answered Oct 02 '22 21:10

Reti43