최근에 this question에 최적의 단어 줄 바꿈을위한 함수를 생성하고이 Python 스크립트에서 찾고있는 응답을 받았습니다. 불행히도, 저는 파이썬을 말하지 않습니다. : D 누군가 이것을 Objective-C로 변환하도록 도울 수 있습니까?Python 스크립트를 Objective-C로 변환
는 _
Code. I took the liberty of modifying the DP always to return exactly n lines, at the cost of increasing the running time from O(#words ** 2) to O(#words ** 2 * n).
def minragged(text, n=3):
"""
>>> minragged('Just testing to see how this works.')
['Just testing', 'to see how', 'this works.']
>>> minragged('Just testing to see how this works.', 10)
['', '', 'Just', 'testing', 'to', 'see', 'how', 'this', 'works.', '']
"""
words = text.split()
cumwordwidth = [0]
# cumwordwidth[-1] is the last element
for word in words:
cumwordwidth.append(cumwordwidth[-1] + len(word))
totalwidth = cumwordwidth[-1] + len(words) - 1 # len(words) - 1 spaces
linewidth = float(totalwidth - (n - 1))/float(n) # n - 1 line breaks
def cost(i, j):
"""
cost of a line words[i], ..., words[j - 1] (words[i:j])
"""
actuallinewidth = max(j - i - 1, 0) + (cumwordwidth[j] - cumwordwidth[i])
return (linewidth - float(actuallinewidth)) ** 2
# best[l][k][0] is the min total cost for words 0, ..., k - 1 on l lines
# best[l][k][1] is a minimizing index for the start of the last line
best = [[(0.0, None)] + [(float('inf'), None)] * len(words)]
# xrange(upper) is the interval 0, 1, ..., upper - 1
for l in xrange(1, n + 1):
best.append([])
for j in xrange(len(words) + 1):
best[l].append(min((best[l - 1][k][0] + cost(k, j), k) for k in xrange(j + 1)))
lines = []
b = len(words)
# xrange(upper, 0, -1) is the interval upper, upper - 1, ..., 1
for l in xrange(n, 0, -1):
a = best[l][b][1]
lines.append(' '.join(words[a:b]))
b = a
lines.reverse()
return lines
if __name__ == '__main__':
import doctest
doctest.testmod()
모든 들여 쓰기를 수행했습니다. 들여 쓰기는 파이썬의 문법의 일부입니다. 중괄호로 묶는 대신에 들여 쓰기를하십시오. – slezica
질문을 편집하고 코드의 형식을 올바르게 지정하십시오 (또는 작성한 사람에게 들여 쓰기 버전을 제공하도록 요청하십시오). 들여 쓰기가없는 파이썬 코드를 읽는 것은 불가능합니다. 이는 C 코드에서'{'와'}를 모두 제거하는 것과 같습니다. – ThiefMaster
Yikes! 깨닫지 못 했어. 원래 코드는 여기에 게시됩니다 : http://stackoverflow.com/questions/5059956/algorithm-to-divide-text-into-3-evenly-sized-groups –