-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbalance_newlines.py
executable file
·40 lines (34 loc) · 1.16 KB
/
balance_newlines.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env python
import sys
def main():
def width(lines):
return max(map(len, [' '.join(l) for l in lines]))
lines = [x.split(' ') for x in sys.stdin.read().strip().split('\n')]
print >>sys.stderr, 'Before - max width:', width(lines)
making_progress = True
while making_progress:
making_progress = False
for i, l in enumerate(lines):
if not len(l):
continue
if i > 0:
ow = width(lines[i-1:i+1])
lines[i-1].append(l.pop(0))
nw = width(lines[i-1:i+1])
if nw < ow:
making_progress = True
break
l.insert(0, lines[i-1].pop(-1))
if i < len(lines) - 1:
ow = width(lines[i:i+2])
lines[i+1].insert(0, l.pop(-1))
nw = width(lines[i:i+2])
if nw < ow:
making_progress = True
break
l.append(lines[i+1].pop(0))
print >>sys.stderr, 'After - max width:', width(lines)
for l in lines:
print ' '.join(l)
if __name__ == '__main__':
main()