[Python] problem in solving closest palindrom number

Discussão em 'Python' iniciado por Stack, Março 16, 2025.

  1. Stack

    Stack Membro Participativo

    I want to solve the following problem: Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.

    The closest is defined as the absolute difference minimized between two integers. Here is what I have tried:

    def nearestPalindromic(n: str) -> str:
    # Convert input string n to integer
    original_n = int(n)

    # Calculate the length of the number as a string
    str_n = str(original_n)
    length = len(str_n)

    # Special case: single digit numbers
    if length == 1:
    return str(original_n)

    # Create the base palindrome by mirroring the left half
    left_half = str_n[:(length + 1) // 2] # Left half including middle if odd
    mirrored = int(left_half + left_half[-(length // 2):][::-1])

    # Create candidates by modifying the left half
    left_num = int(left_half)

    lower_half = str(left_num - 1) # Decrease left half
    upper_half = str(left_num + 1) # Increase left half

    lower_pal = int(lower_half + lower_half[-(length // 2):][::-1])
    upper_pal = int(upper_half + upper_half[-(length // 2):][::-1])

    # Handle edge cases like 1000 -> 999, or 9999 -> 10001
    edge_case = 10 ** (length - 1) - 1 # 999 for 1000
    large_case = 10 ** length + 1 # 10001 for 9999

    # List of all candidates
    candidates = [mirrored, lower_pal, upper_pal, edge_case, large_case]

    # Exclude the original number from candidates
    candidates = [c for c in candidates if c != original_n]

    # Find the closest palindrome using the key that compares by absolute difference first,
    # and by value second for ties
    closest = min(candidates, key=lambda x: (abs(x - original_n), x))

    # Return the result as a string
    return str(closest)


    but I get this error:

    Input
    n =
    "123"
    Output
    122
    Expected
    "121"

    Continue reading...

Compartilhe esta Página