Clean python code


  • 1
    class Solution(object):
        def formLine(self, words, size, maxWidth):
            if size == 1:
                return words[0] + ' ' * (maxWidth - len(words[0]))
    
            base, mod = divmod(maxWidth - sum(map(len, words)), size - 1)
            return ''.join(words[:1] + map(''.join, itertools.izip(
                itertools.chain(
                    itertools.repeat(' ' * (base + 1), mod),
                    itertools.repeat(' ' * base, size - 1 - mod)),
                words[1:]
            )))
    
        def formLastLine(self, words, size, maxWidth):
            r = ' '.join(words)
            return r + ' ' * (maxWidth - len(r))
    
        def fullJustify(self, words, maxWidth):
            i, n, L, lines = 0, len(words), maxWidth, []
            while i < n:
                length, j = 0, i
                while i < n:
                    add = len(words[i]) + (length != 0)
                    if length + add > L:
                        break
                    length += add
                    i += 1
                lines.append([j, i])
    
            return [f(words[j:i], i - j, L) for f, (j, i) in itertools.izip(
                itertools.chain(
                    itertools.repeat(self.formLine, len(lines) - 1),
                    [self.formLastLine]
                ), lines)
            ]

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.