Write a python function `dedent(str)` that takes as input a string of python code and de-dents it maximally. Lines that are entirely blank don't count.
Write a python function `dedent(str)` that takes as input a string of python code and de-dents it maximally. Lines that are entirely blank don't count.
One acceptable solution is to first determine the smallest number of leading whitespace characters in any non‐blank line and then remove that many characters from every line. (Blank lines are left alone.) For example: -------------------------------------------------- def dedent(code): """ Remove the common leading whitespace from every non‐blank line in a Python code string. Args: code (str): A string containing Python code. Returns: str: The code with its lines de-dented. """ # Split the text into lines. lines = code.splitlines() # Find the number of leading spaces for each non-blank line. min_indent = None for line in lines: # Skip lines that are blank. if line.strip(): # Count the number of leading whitespace characters. count = len(line) - len(line.lstrip()) if min_indent is None or count < min_indent: min_indent = count # If no non-blank line was found, just return the code unchanged. if min_indent is None: return code # Remove the min_indent from every line that isn't blank. dedented_lines = [] for line in lines: # Only remove indentation from non-blank lines. if line.strip(): dedented_lines.append(line[min_indent:]) else: # For blank lines, just keep an empty string. dedented_lines.append("") # Reconstruct the code from the dedented lines. return "\n".join(dedented_lines) # Example usage: if __name__ == "__main__": sample_code = """ def hello(): print("Hello, world!") """ print("Original code:") print(sample_code) print("Dedented code:") print(dedent(sample_code)) -------------------------------------------------- How it works: 1. We split the code into lines. 2. For each non-blank line (one that isn’t just spaces or empty), we count the leading spaces. 3. We keep the smallest count found. 4. Finally, we strip that many characters from the beginning of every non‑blank line and return the resulting code. This function works similarly to Python’s built‑in textwrap.dedent, but it explicitly ignores blank lines when determining the common indent.
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #!/usr/bin/env python3 def dedent(code): """ Remove the common leading whitespace from every non‐blank line in a Python code string. Args: code (str): A string containing Python code. Returns: str: The code with its lines de-dented. """ # Split the text into lines. lines = code.splitlines() # Find the number of leading spaces for each non-blank line. min_indent = None for line in lines: # Skip lines that are blank. if line.strip(): # Count the number of leading whitespace characters. count = len(line) - len(line.lstrip()) if min_indent is None or count < min_indent: min_indent = count # If no non-blank line was found, just return the code unchanged. if min_indent is None: return code # Remove the min_indent from every line that isn't blank. dedented_lines = [] for line in lines: # Only remove indentation from non-blank lines. if line.strip(): dedented_lines.append(line[min_indent:]) else: # For blank lines, just keep an empty string. dedented_lines.append("") # Reconstruct the code from the dedented lines. return "\n".join(dedented_lines) # Example usage: if __name__ == "__main__": sample_code = """ def hello(): print("Hello, world!") """ print("Original code:") print(sample_code) print("Dedented code:") print(dedent(sample_code)) |
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | #!/usr/bin/env python3 def dedent(code): """ Remove the common leading whitespace from every non‐blank line in a Python code string. Args: code (str): A string containing Python code. Returns: str: The code with its lines de-dented. """ # Split the text into lines. lines = code.splitlines() # Find the number of leading spaces for each non-blank line. min_indent = None for line in lines: # Skip lines that are blank. if line.strip(): # Count the number of leading whitespace characters. count = len(line) - len(line.lstrip()) if min_indent is None or count < min_indent: min_indent = count # If no non-blank line was found, just return the code unchanged. if min_indent is None: return code # Remove the min_indent from every line that isn't blank. dedented_lines = [] for line in lines: # Only remove indentation from non-blank lines. if line.strip(): dedented_lines.append(line[min_indent:]) else: # For blank lines, just keep an empty string. dedented_lines.append("") # Reconstruct the code from the dedented lines. return "\n".join(dedented_lines) # Example usage: if __name__ == "__main__": sample_code = """ def hello(): print("Hello, world!") """ print("Original code:") print(sample_code) print("Dedented code:") print(dedent(sample_code)) answer = dedent(''' print("hello") print("world") if True: print("true") else: print("false")''') expected = """print("hello") print("world") if True: print("true") else: print("false")""" assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' print('All tests passed') |
1 2 3 4 5 6 7 | Original code: def hello(): print("Hello, world!")</p> <p>Dedented code: def hello(): print("Hello, world!") All tests passed |
Testing if the previous output contains the string All tests passed
: True
Write a python function `dedent(str)` that takes as input a string of python code and de-dents it maximally. Lines that are entirely blank don't count.
Write a python function `dedent(str)` that takes as input a string of python code and de-dents it maximally. Lines that are entirely blank don't count.
Below is one acceptable solution. It works by processing each non‐blank line to find the minimum indent (i.e. the number of leading whitespace characters) and then removing that amount from the beginning of every line: ------------------------------------------------ def dedent(code): """ Remove any common leading whitespace from every line in `code`. Lines that are entirely whitespace are ignored when computing the common indent. """ # Split into individual lines. lines = code.splitlines() # Determine the minimum leading whitespace for nonblank lines. indents = [] for line in lines: # Skip blank lines if line.strip(): # Measure the number of leading whitespace characters. indent = len(line) - len(line.lstrip()) indents.append(indent) # The maximum de-denting possible is given by the smallest indent. common_indent = min(indents) if indents else 0 # Remove the common indent from each line dedented_lines = [] for line in lines: # For blank lines, keep them as is. if line.strip(): dedented_lines.append(line[common_indent:]) else: dedented_lines.append(line) # Recombine the lines return "\n".join(dedented_lines) # Example usage: if __name__ == "__main__": code = """ def hello(): print("Hello, world!") """ print("Original code:") print(repr(code)) print("\nDedented code:") print(repr(dedent(code))) ------------------------------------------------ Explanation: 1. We split the string into lines. 2. For each non-blank line (ignoring lines that are completely empty or contain only whitespace), we compute its indent by comparing the length of the line with the length after stripping left whitespace. 3. The minimum indent (common_indent) is computed over all non-blank lines. 4. Each non-blank line is then sliced from the position common_indent onward. Blank lines are left unchanged. 5. Finally, the list of dedented lines is rejoined into a single string. This function behaves similarly to Python’s built-in textwrap.dedent but is written manually.
I extracted the following code from that output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | #!/usr/bin/env python3 def dedent(code): """ Remove any common leading whitespace from every line in `code`. Lines that are entirely whitespace are ignored when computing the common indent. """ # Split into individual lines. lines = code.splitlines() # Determine the minimum leading whitespace for nonblank lines. indents = [] for line in lines: # Skip blank lines if line.strip(): # Measure the number of leading whitespace characters. indent = len(line) - len(line.lstrip()) indents.append(indent) # The maximum de-denting possible is given by the smallest indent. common_indent = min(indents) if indents else 0 # Remove the common indent from each line dedented_lines = [] for line in lines: # For blank lines, keep them as is. if line.strip(): dedented_lines.append(line[common_indent:]) else: dedented_lines.append(line) # Recombine the lines return "\n".join(dedented_lines) # Example usage: if __name__ == "__main__": code = """ def hello(): print("Hello, world!") """ print("Original code:") print(repr(code)) print("\nDedented code:") print(repr(dedent(code))) |
Running the following program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | #!/usr/bin/env python3 def dedent(code): """ Remove any common leading whitespace from every line in `code`. Lines that are entirely whitespace are ignored when computing the common indent. """ # Split into individual lines. lines = code.splitlines() # Determine the minimum leading whitespace for nonblank lines. indents = [] for line in lines: # Skip blank lines if line.strip(): # Measure the number of leading whitespace characters. indent = len(line) - len(line.lstrip()) indents.append(indent) # The maximum de-denting possible is given by the smallest indent. common_indent = min(indents) if indents else 0 # Remove the common indent from each line dedented_lines = [] for line in lines: # For blank lines, keep them as is. if line.strip(): dedented_lines.append(line[common_indent:]) else: dedented_lines.append(line) # Recombine the lines return "\n".join(dedented_lines) # Example usage: if __name__ == "__main__": code = """ def hello(): print("Hello, world!") """ print("Original code:") print(repr(code)) print("\nDedented code:") print(repr(dedent(code))) answer = dedent(''' print("hello") print("world") if True: print("true") else: print("false")''') expected = """print("hello") print("world") if True: print("true") else: print("false")""" assert answer == expected, f'Wrong answer; got {answer} instead of {expected}' print('All tests passed') |
Original code:
'\n def hello():\n print("Hello, world!")\n '
Dedented code:
'\ndef hello():\n print("Hello, world!")\n '
All tests passed
Testing if the previous output contains the string All tests passed
: True