# Line Leveling Code (Based on Raggedness)

a guest
Dec 5th, 2015
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. import itertools
2.
3. def comp_cost(split, combination):
4.     s_list = []
5.     n = 0
6.     cost = 0
7.     for x in combination:
8.         s_list.append(' '.join(split[n:n+x]))
9.         n += x
10.     for x in s_list:
11.         cost += (len(x)) ** 2
12.     return cost
13.
14. def line_level(s, lines):
15.     cost = 100000
16.     split = s.split(' ')
17.     if lines > len(split):  #Not enough lines for at least 1 word on each line
18.         answer = tuple([1] * len(split) + [0] * (lines - len(split)))
20.     else:
21.         num_list = range(1, len(split))         #Brute force: The combinations of numbers that add up to the number of words
22.         combinations = filter(lambda y: sum(y) == len(split),
23.                               [x for x in itertools.combinations_with_replacement(num_list, lines)])
24.         combinations = list(set(combinations))              #Remove duplicates
25.         for x in combinations:                              #A set of numbers that adds up to the number of words
26.             for y in list(set(itertools.permutations(x))):  #Remove duplicates; permutations is needed to test each combination
27.                 if comp_cost(split, y) < cost:
28.                     cost = comp_cost(split, y)
30.     print('Words:    {},  Lines: {}'.format(len(split), lines))
31.     print('Min Cost: {}'.format(cost))
32.     n = 0
34.         print(' '.join(split[n:n+x]))
35.         n += x
36.
37. line_level('The quick brown fox jumped over the lazy dog.', 5)
38. print('')
39. line_level('The quick brown fox jumped over the lazy dog.', 4)
40. print('')
41. line_level('The quick brown fox jumped over the lazy dog.', 3)
42. print('')
43. line_level('The quick.', 3)