Source

codeeval_challenges / 002_LongestLines / longest_lines.py

# On CodeEval, test cases are read in from a file which is the first argument to your program
# Open the file and read in line by line. Each line represents a different test case
# (unless given different instructions in the challenge description)

import sys

filename = sys.argv[1]
file_handle = open(filename, 'r')

n_lines = int(file_handle.next().strip())

lines = []
for line in file_handle:
    line = line.strip()
    
    ## skip empty lines, append others to list
    if line != '':
        lines.append(line)

## sort non-empty lines by length
sorted_lines = sorted(
    lines, 
    cmp=lambda x, y: cmp(len(y), len(x))
)

for line in sorted_lines[:n_lines]: 
    print line

file_handle.close()