Description:
Write a program to read a multiple line text file and write the 'N' longest lines to stdout. Where the file to be read is specified on the command line.
Input sample:
Your program should read an input file (the first argument to your program). The first line contains the value of the number 'N' followed by multiple lines. You may assume that the input file is formatted correctly and the number on the first line i.e. 'N'
is a valid positive integer.e.g.
2 Hello World CodeEval Quick Fox A San FranciscoNOTE: For solutions in JavaScript, assume that there are 8 lines of input (i.e. line 1 will be N and the next 7 lines will be the input lines
Output sample:
The 'N' longest lines, newline delimited. Do NOT print out empty lines. Ignore all empty lines in the input. Ensure that there are no trailing empty spaces on each line you print. Also ensure that the lines are printed out in decreasing order of length i.e. the output should be sorted based on their length e.g.
San Francisco Hello World
解决方案:
if __name__ == "__main__":
argv = sys.argv
inf = open(argv[1],'r')
strings = inf.readlines()
k = 0
N = int(strings[0]) + 1
num = len(strings)
#print num
for i in range(1,num):
#print i,strings[i]
#print strings
x = i
for j in range(i+1,num):
print x,len(strings[x]),strings[x]
print j,len(strings[j]),strings[j]
if len(strings[x]) < len(strings[j]):
x = j
#print x,i
if x != i:
#print x,i
#print strings[i],strings[x]
tmp = strings[i]
strings[i] = strings[x]
strings[x] = tmp
#print "test:",strings[i]
#print strings
本文介绍了一个程序设计问题的解决方法,该程序能够读取指定文件,并找出其中的N个最长行进行输出。文章提供了完整的代码实现,通过逐行比较字符串长度的方式实现了排序。
&spm=1001.2101.3001.5002&articleId=8457685&d=1&t=3&u=a05e8f1278de427fabf32ba52db47f42)
1313

被折叠的 条评论
为什么被折叠?



