The python implementation gets the smallest elements in a sequence
- 2020-04-02 14:06:50
- OfStack
This article illustrates a python implementation that fetches the smallest elements in a sequence. Share with you for your reference.
Specific methods are as follows:
import heapq
import random
def issorted(data):
data = list(data)
heapq.heapify(data)
while data:
yield heapq.heappop(data)
alist = [x for x in range(10)]
random.shuffle(alist)
print 'the origin list is',alist
print 'the min in the list is'
for x in issorted(alist):
print x,
The results of the program are as follows:
the origin list is [2, 3, 4, 9, 8, 5, 1, 6, 0, 7]
the min in the list is
0 1 2 3 4 5 6 7 8 9
Heapq module and random module are used. Heapq binary tree is often used to deal with priority sequence problems.
There's an easier way:
Print heapq.nsmallest(3,alist)# prints the smallest three elements in the alist list, and compares them alphabetically if they are letters
Interested friends can test the running of this article example, I believe that this article has a certain reference value for you to learn Python program design.