【发布时间】:2012-02-12 03:04:53
【问题描述】:
这是作业,所以我必须尽量少用python函数,但仍然允许计算机有效地处理一百万个数字的列表。
#!/usr/bin/python3
#Find the 10 largest integers
#Don't store the whole list
import sys
import heapq
def fOpen(fname):
try:
fd = open(fname,"r")
except:
print("Couldn't open file.")
sys.exit(0)
all = fd.read().splitlines()
fd.close()
return all
words = fOpen(sys.argv[1])
numbs = map(int,words)
print(heapq.nlargest(10,numbs))
li=[]
count = 1
#Make the list
for x in words:
li.append(int(x))
count += 1
if len(li) == 10:
break
#Selection sort, largest-to-smallest
for each in range(0,len(li)-1):
pos = each
for x in range(each+1,10):
if li[x] > li[pos]:
pos = x
if pos != each:
li[each],li[pos] = li[pos],li[each]
for each in words:
print(li)
each = int(each)
if each > li[9]:
for x in range(0,9):
pos = x
if each > li[x]:
li[x] = each
for i in range(x+1,10):
li[pos],li[i] = li[i],li[pos]
break
#Selection sort, largest-to-smallest
for each in range(0,len(li)-1):
pos = each
for x in range(each+1,10):
if li[x] > li[pos]:
pos = x
if pos != each:
li[each],li[pos] = li[pos],li[each]
print(li)
代码几乎按照我想要的方式运行。我试图从前 10 位数字创建一个列表。对它们进行排序,使其按降序排列。然后让 python 只检查列表,如果数字大于较小的数字(而不是读取列表 10(len(x))。
这是我应该得到的输出:
>>>[9932, 9885, 9779, 9689, 9682, 9600, 9590, 9449, 9366, 9081]
这是我得到的输出:
>>>[9932, 9689, 9885, 9779, 9682, 9025, 9600, 8949, 8612, 8575]
【问题讨论】:
-
您真的需要对整个列表进行排序吗?或者您只需要最后的前 10 个数字?
-
我想我只需要前10名。
-
可能你的老师更喜欢 4 个字符的缩进而不是 8 个
-
@SethRainerKania 你看到我在你之前的问题上发布的选择排序算法了吗?