Longest Lines(Python版)

本文介绍了一个程序设计问题的解决方法,该程序能够读取指定文件,并找出其中的N个最长行进行输出。文章提供了完整的代码实现,通过逐行比较字符串长度的方式实现了排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 Francisco
NOTE: 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

解决方案:

#问题的目标是输出给定字符串集合中的N个最常的字符串
#处理方案为:将所有字符串按长度进行排序
import sys

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
        for i in range(1,N):
               print strings[i][:-1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值