From 2b3f50077f3ef064983dcf9473e020f13310be13 Mon Sep 17 00:00:00 2001 From: Marius-Juston Date: Sun, 30 Mar 2025 20:56:28 -0500 Subject: [PATCH 1/2] minor optimizations for simulataneously comptuing min + max + normalization --- Lib/textwrap.py | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/Lib/textwrap.py b/Lib/textwrap.py index bb6a1186316275..cc7b3df303a2a6 100644 --- a/Lib/textwrap.py +++ b/Lib/textwrap.py @@ -432,15 +432,28 @@ def dedent(text): lines = text.split('\n') # Get length of leading whitespace, inspired by ``os.path.commonprefix()``. - non_blank_lines = [l for l in lines if l and not l.isspace()] - l1 = min(non_blank_lines, default='') - l2 = max(non_blank_lines, default='') - margin = 0 + l1 = None + l2 = None + for i, line in enumerate(lines): + # Compute min + max concurrently + normalize others + if line and not line.isspace(): + if l1 is None or line < l1: + l1 = line + if l2 is None or line > l2: + l2 = line + else: + lines[i] = '' + + if l1 is None: + l1 = '' + for margin, c in enumerate(l1): if c != l2[margin] or c not in ' \t': break + else: + return '\n'.join(lines) - return '\n'.join([l[margin:] if not l.isspace() else '' for l in lines]) + return '\n'.join([line[margin:] for line in lines]) def indent(text, prefix, predicate=None): From d30196edac8530c649eee7c793b06348b8cce8ad Mon Sep 17 00:00:00 2001 From: Marius-Juston Date: Mon, 31 Mar 2025 05:37:02 -0500 Subject: [PATCH 2/2] replacing if with elseif --- Lib/textwrap.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/Lib/textwrap.py b/Lib/textwrap.py index cc7b3df303a2a6..7aa2a82af2fcc3 100644 --- a/Lib/textwrap.py +++ b/Lib/textwrap.py @@ -432,26 +432,28 @@ def dedent(text): lines = text.split('\n') # Get length of leading whitespace, inspired by ``os.path.commonprefix()``. - l1 = None - l2 = None + val = False for i, line in enumerate(lines): # Compute min + max concurrently + normalize others if line and not line.isspace(): - if l1 is None or line < l1: - l1 = line - if l2 is None or line > l2: - l2 = line + if val: + if line < l1: + l1 = line + elif line > l2: + l2 = line + else: + val = True + l1 = l2 = line + else: lines[i] = '' - if l1 is None: - l1 = '' + if not val or not l1: + return '\n'.join(lines) for margin, c in enumerate(l1): if c != l2[margin] or c not in ' \t': break - else: - return '\n'.join(lines) return '\n'.join([line[margin:] for line in lines])