Created
October 9, 2014 15:09
-
-
Save gulan/8cf5a2d2aa27084d362f to your computer and use it in GitHub Desktop.
r/dailyprogrammer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /usr/bin/env python2 | |
| def input_to_words(fh,col_width): | |
| for line in fh: | |
| for word in line.split(' '): | |
| w = word.strip() | |
| if len(w) > col_width: | |
| raise Exception, "%r is longer that column width" % w | |
| yield w | |
| def words_to_field(source,col_width): | |
| field = [] | |
| def field_len(fld): | |
| # joined-up size | |
| assert len(fld) > 0 | |
| spaces = len(fld)-1 # n-1, since spaces are between words | |
| chars = sum([len(w) for w in fld]) | |
| return spaces + chars | |
| def joinup(): | |
| x = ' '.join(field) | |
| fill = col_width - len(x) | |
| return x + (' ' * fill) | |
| for word in source: | |
| nx = field + [word] | |
| if field_len(nx) > col_width: | |
| yield joinup() | |
| field = [word] | |
| else: | |
| field = nx | |
| if field: | |
| yield joinup() | |
| def padding(field_list,ncols,col_width): | |
| # fill the rightmost column to be the same length as the others | |
| n = len(field_list) | |
| rem = n % ncols | |
| blank = ' ' * col_width | |
| return field_list + [blank for i in range(rem)] | |
| if __name__ == '__main__': | |
| fh = open('input.txt') | |
| cols, width, space = [int(i) for i in fh.readline().split()] | |
| spacer = ' ' * space | |
| fields = list(words_to_field(input_to_words(fh,width),width)) | |
| fields = padding(fields,cols,width) | |
| depth = len(fields) / cols | |
| ix = [c*depth for c in range(cols)] # an array of indexes | |
| while ix[0] < depth: | |
| x = [fields[ix[j]] for j in range(cols)] | |
| line = spacer.join(x) | |
| print line | |
| ix = [i+1 for i in ix] | |
| fh.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment