-3

I created this code to enter a string of integers by a user. I am trying to write a loop to find the second smallest number in de list. How do I finish this?

numbers_input = raw_input('Insert numbers seperated by a space')
numbers_strings = numbers_input.split() 
numbers_list = map(int, numbers_strings)

for x in numbers_list:
user2989433
  • 53
  • 1
  • 6

1 Answers1

1

Its what that heapq.nsmallest is for:

>>> import heapq
>>> l=[10, 12, 2, 2, 5 ,15]
>>> print(heapq.nsmallest(2, set(l))) [1]
5

Note that set(l) is for remove duplicate indices ! (thank of Jon Clements for reminding in comment)

Also you can use sorted(iterable)[:n][1] for find second smallest that sorted(iterable)[:n] give you n smallest indices !

The most important feature of a heap is that heap[0] is always the smallest item. More‐ over, subsequent items can be easily found using the heapq.heappop() method, which pops off the first item and replaces it with the next smallest item (an operation that requires O(log N) operations where N is the size of the heap)

source code of nsmallest

def nsmallest(n, iterable):
    """Find the n smallest elements in a dataset.

Equivalent to:  sorted(iterable)[:n]
"""
if n < 0:
    return []
it = iter(iterable)
result = list(islice(it, n))
if not result:
    return result
_heapify_max(result)
_heappushpop = _heappushpop_max
for elem in it:
    _heappushpop(result, elem)
result.sort()
return result
Mazdak
  • 105,000
  • 18
  • 159
  • 188