好的,这里!我刚完成这个程序。它运作良好,但结果不是我想要的。 这是我的全部代码:
#----------class of queue----------
class queue:
def __init__(self):
self._queue = []
def __str__(self):
sstr = ""
for i in self._queue:
sstr += str(i)
sstr += ", "
return sstr
def __len__(self):
return len(self._queue)
def after(self):
return self._queue.pop(0)
def add(self, i):
self._queue.append(i)
#----------radix sort----------
def set_output():
output_list = []
for i in range (10):
output_list.append(queue())
return output_list
def set_radix(lists):
output_list = set_output()
for number in lists:
a = number[2]
output_list[int(a)].add(number)
return output_list
def sec_radix(input_list, i):
output_list = set_output()
for queue in input_list:
while len(queue) > 0:
num = queue.after()
a = num[i]
output_list[int(a)].add(num)
return output_list
def done_radix(num_list):
return sec_radix(sec_radix(set_radix(num_list), 1), 0)
#----------read and write file----------
def readfile(infile):
print "Reading files, please wait..."
f = open(infile, "r")
lineList = f.readlines()
f.close()
outputList = []
for line in lineList:
line = line.strip()
outputList.append(line.split(" "))
print "Reading finished!"
return outputList
def writefile(outfile, nums):
print "Writing files, please wait..."
output = new_output(nums)
f = open(outfile, "w")
f.write(output)
print "Writing finished!"
def new_output(three_list):
output = ""
for queue_list in three_list:
for numqueue in queue_list:
while len(numqueue) > 0:
output += numqueue.after()
output += " "
output += "\n"
return output
#----------main function----------
def main():
infile = readfile("radix.in")
final_list = []
for num_list in infile:
print "Sorting..."
final_list.append(done_radix(num_list))
print "Sorting finished!"
writefile("radix.out", final_list)
main()
这里的输入和输出应该是三行:
表示radix.in:
第1行:467 119 635 231 234 858 第2行:786 463 715 745 729 574 856 806 339 106 487 第3行:798 791 392 916 177 115 948 871 525
表示radix.out:
第1行:119 231 234 467 635 858 第2行:106 339 463 487 574 715 729 745 786 806 856 第3行:115 177 392 525 791 798 871 916 948
运行此程序时,您需要在同一路径中有两个文件(同一文件夹)。当你完成运行时,结果应该看起来像上面的radix.out, 这是真的有线...它应该只创建三行,但有26行,这意味着它在排序时每个新行开始一个数字。
如何打印出如上所述的三行。
答案 0 :(得分:0)
改变这个:
def new_output(three_list):
output = ""
for queue_list in three_list:
for numqueue in queue_list:
while len(numqueue) > 0:
output += numqueue.after()
output += " "
output += "\n"
return output
对此(请注意最后一行中的缩进!):
def new_output(three_list):
output = ""
for queue_list in three_list:
for numqueue in queue_list:
while len(numqueue) > 0:
output += numqueue.after()
output += " "
output += "\n"
return output
答案 1 :(得分:0)
也许用以下内容写入outfile:
with open('radix.out', 'w') as outfile:
for sublist in final_list:
list1 = (str(element).strip() for element in sublist)
list2 = (element for element in list1 if element)
list3 = (element.rstrip(',') for element in list2)
string = ', '.join(list3)
outfile.write('{}\n'.format(string))
顺便说一下,使用list_.sort()可能比编写自己的基数排序更好。这有两个原因: