Thursday 15 March 2012

Python - Find second smallest number -



Python - Find second smallest number -

i found code on site find sec largest number:

def second_largest(numbers): m1, m2 = none, none x in numbers: if x >= m1: m1, m2 = x, m1 elif x > m2: m2 = x homecoming m2

source: get sec largest number in list in linear time

is possible modify code find sec smallest number? example

print second_smallest([1, 2, 3, 4]) 2

the function can indeed modified find sec smallest:

def second_smallest(numbers): m1, m2 = float('inf'), float('inf') x in numbers: if x <= m1: m1, m2 = x, m1 elif x < m2: m2 = x homecoming m2

the old version relied on python 2 implementation detail none sorted before else (so tests 'smaller'); replaced using float('inf') sentinel, infinity tests larger other number. ideally original function should have used float('-inf') instead of none there, not tied implementation detail other python implementations may not share.

demo:

>>> def second_smallest(numbers): ... m1, m2 = float('inf'), float('inf') ... x in numbers: ... if x <= m1: ... m1, m2 = x, m1 ... elif x < m2: ... m2 = x ... homecoming m2 ... >>> print second_smallest([1, 2, 3, 4]) 2

python

No comments:

Post a Comment