Skip to content

Commit 8337ce5

Browse files
committed
Improve cjk_slices() complexity from O(n^2) to O(n) (Thanks to INADA Naoki)
1 parent bfdfb22 commit 8337ce5

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

Lib/textwrap.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -446,11 +446,12 @@ def cjk_slices(text, index):
446446
return text[:index], text[index:]
447447
if cjk_len(text) <= index:
448448
return text, ''
449-
i = 1
450-
# <= and i-1 to catch the last double length char of odd line
451-
while cjk_len(text[:i]) <= index:
452-
i = i + 1
453-
return text[:i-1], text[i-1:]
449+
width = 0
450+
for i, char in enumerate(text):
451+
width = width + cjk_wide(char) + 1
452+
if width > index:
453+
break
454+
return text[:i], text[i:]
454455

455456

456457
# -- Loosely related functionality -------------------------------------

0 commit comments

Comments
 (0)