操作顺序
→到目前为止输入的最大值为20。
→如果第21个值> Minheap.getMin()
→→从minheap中拉出最小的一个。
→→将第21个值添加到minheap。
→否则忽略第21个值。
下面我的代码想知道我可能有什么错误...
class input:
def __init__(self, file):
self.file = file
self.length = 0
self.used = 0
self.buffer = " "
def read(self) :
if self.used < self.length:
c = self.buffer[self.used]
self.used += 1
return c
else:
self.buffer = self.file.read( 20 )
self.length = len( self.buffer)
if self.length == 0:
return -1
else:
c = self.buffer[0]
self.used = 1
return c
class Minheap:
def add(self, x):
self.list.append(x)
def getMin( self ):
if len(self.list) <= 0:
return None
else:
return self.list[0]
def removeMin( self ):
if len(self.list) <= 0:
return None
else:
self.swap( 0, -1)
return self.list.pop()
答案 0 :(得分:1)
该计划符合您的要求:
import sys
from heapq import nsmallest
result = nsmallest(20, sys.stdin, int)
print(result)