问题:代码应该采用一个文件(每行包含一个整数值),打印(未排序)整数 值,对它们进行排序,然后打印已排序的值。
有什么不合适的吗?我知道我可以测试它并且我测试了selectionSort,它运行良好。但我真的不知道如何测试它是否成功获取文件并完成它应该做的事情。
谢谢
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
答案 0 :(得分:1)
您的选择排序似乎是正确的,但之前的部分有问题:
(我假设这是Python 2.X,如果不忽略我的回答)
raw_input
not input
. 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)
答案 1 :(得分:0)
将第3行更改为
alist = [int(line.strip()) for line in file.readlines()]
这
alist = [int(line) for line in file.readlines()]