Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import itertools
- def comp_cost(split, combination):
- s_list = []
- n = 0
- cost = 0
- for x in combination:
- s_list.append(' '.join(split[n:n+x]))
- n += x
- for x in s_list:
- cost += (len(x)) ** 2
- return cost
- def line_level(s, lines):
- cost = 100000
- split = s.split(' ')
- if lines > len(split): #Not enough lines for at least 1 word on each line
- answer = tuple([1] * len(split) + [0] * (lines - len(split)))
- cost = comp_cost(split, answer)
- else:
- num_list = range(1, len(split)) #Brute force: The combinations of numbers that add up to the number of words
- combinations = filter(lambda y: sum(y) == len(split),
- [x for x in itertools.combinations_with_replacement(num_list, lines)])
- combinations = list(set(combinations)) #Remove duplicates
- for x in combinations: #A set of numbers that adds up to the number of words
- for y in list(set(itertools.permutations(x))): #Remove duplicates; permutations is needed to test each combination
- if comp_cost(split, y) < cost:
- cost = comp_cost(split, y)
- answer = y
- print('Words: {}, Lines: {}'.format(len(split), lines))
- print('Min Cost: {}'.format(cost))
- n = 0
- for x in answer:
- print(' '.join(split[n:n+x]))
- n += x
- line_level('The quick brown fox jumped over the lazy dog.', 5)
- print('')
- line_level('The quick brown fox jumped over the lazy dog.', 4)
- print('')
- line_level('The quick brown fox jumped over the lazy dog.', 3)
- print('')
- line_level('The quick.', 3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement