Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Find second smallest number

Tags:

python

I found this code on this site to find the second largest number:

def second_largest(numbers):
    m1, m2 = None, None
    for x in numbers:
        if x >= m1:
            m1, m2 = x, m1
        elif x > m2:
            m2 = x
    return m2

Source: Get the second largest number in a list in linear time

Is it possible to modify this code to find the second smallest number? So for example

print second_smallest([1, 2, 3, 4])
2
like image 278
user2971812 Avatar asked Nov 06 '14 12:11

user2971812


People also ask

How do you find the smallest number in Python?

Use Python's min() and max() to find smallest and largest values in your data. Call min() and max() with a single iterable or with any number of regular arguments.

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

A Simple Solution is to sort the array in increasing order. The first two elements in the sorted array would be the two smallest elements. In this approach, if the smallest element is present more than one time then we will have to use a loop for printing the unique smallest and second smallest elements.


1 Answers

a = [6,5,4,4,2,1,10,1,2,48]
s = set(a) # used to convert any of the list/tuple to the distinct element and sorted sequence of elements
# Note: above statement will convert list into sets 
print sorted(s)[1] 
like image 180
Nita Mandavkar Avatar answered Oct 28 '22 12:10

Nita Mandavkar