Python选择排序 [英] Python selection sort
问题描述
问题:代码应该采用一个文件(每行包含一个整数值),打印(未排序)整数
值,对它们进行排序,然后打印排序值。
Question: The code is supposed to take a file (that contains one integer value per line), print the (unsorted) integer values, sort them, and then print the sorted values.
有什么不合适的吗?我知道我可以测试它,我测试了selectionSort,它运行良好。但我真的不知道如何测试它是否成功获取该文件并完成它应该做的事情。
Is there anything that doesn't look right? I know I could test it and I did test the selectionSort, which worked fine. But I don't really know how I could test whether it successfully takes the file and does what its supposed to do.
谢谢
filename=input('Enter file path:')
file = open(filename, 'r')
alist = [int(line) for line in file.readlines()]
print(alist)
def selectionSort(alist):
for index in range(0, len(alist)):
ismall = index
for i in range(index,len(alist)):
if alist[ismall] > alist[i]:
ismall = i
alist[index], alist[ismall] = alist[ismall], alist[index]
return alist
推荐答案
您的选择排序似乎是正确的,但之前的部分有问题:
Your selection sort seems to be correct but the part before it has issues:
(我假设这是Python 2.X,如果不是忽略我的答案)
(I am assuming this is Python 2.X, if it isn't ignore my answer)
- You need to use
raw_input
notinput
. file.readlines()
doesn't get rid of the\n
at the end of every line. You need to strip it away.
更正后的代码:
filename=raw_input('Enter file path:')
file = open(filename, 'r')
alist = [int(line.strip()) for line in file.readlines()]
print(alist)
这篇关于Python选择排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!