How to reverse a list of characters without affecting the special characters in Python

1 Answer

0 votes
"""
Reverse Only Letters in a List Implementation in Python.
"""

from typing import List

def reverse_only_letters(chars: List[str]) -> None:
    """
    Reverses only the alphabetic characters in a list of characters in-place,
    leaving special characters, spaces, and digits in their original positions.
    
    Args:
        chars (List[str]): The input list of characters to modify.
    """
    if not chars:
        return

    left = 0
    right = len(chars) - 1
    
    # Use a two-pointer approach moving inward from both ends
    while left < right:
        # Advance left pointer until it points to an alphabetic character
        while left < right and not chars[left].isalpha():
            left += 1
            
        # Move right pointer backward until it points to an alphabetic character
        while left < right and not chars[right].isalpha():
            right -= 1
            
        # Swap the valid letters found at both pointers using Python's tuple assignment
        if left < right:
            chars[left], chars[right] = chars[right], chars[left]
            left += 1
            right -= 1


def main() -> None:
    # Input list 
    lst = ['a', '#', 'b', '$', '%', 'c', '&', '*', '(', 'd', 'e', 'f', '!']
    
    print(f"Original: {lst}")
    
    # Apply the reversal function in-place
    reverse_only_letters(lst)
    
    print(f"Reversed: {lst}")


if __name__ == "__main__":
    main()



'''
run:

Original: ['a', '#', 'b', '$', '%', 'c', '&', '*', '(', 'd', 'e', 'f', '!']
Reversed: ['f', '#', 'e', '$', '%', 'd', '&', '*', '(', 'c', 'b', 'a', '!']

'''

 



answered Nov 4 by avibootz
...