[Python] Kaprekar numbers in Python

Discussão em 'Python' iniciado por Stack, Abril 26, 2025.

  1. Stack

    Stack Membro Participativo

    I aas solving a problem on HackerRank and the problem is as follows:

    A modified Kaprekar number is a positive whole number n with d digits, such that when we split its square into two pieces - a right hand piece r with d digits and a left hand piece l that contains the remaining d or d−1 digits, the sum of the pieces is equal to the original number (i.e. l + r = n).

    Alternatively, a modified Kaprekar number is a positive whole number n with 2d digits (if its number of digits is even) or 2d + 1 digits (if its number of digits is odd), such that when we split its square into two pieces, a right hand piece r containing d or d + 1 digits, and a left piece l containing the remaining d digits, the sum of the two pieces is equal to the original number.

    We need to find Kaprekar numbers within a given range. So I wrote the following piece of code:

    def checkIsKaprekar( num ):
    string_num = str(num**2)
    if num == int(string_num[:len(string_num)//2]) + int(string_num[len(string_num)//2:]):
    return True

    kaprekars = [ str(i) for i in range(int(input()),int(input())) if checkIsKaprekar(i) == True ]
    print (' '.join(kaprekars))


    The problem with the above solution is when we pass single digit numbers, they are converted into a string of which the right half is the number itself and the left half is ''. Now I am converting these strings to int(), which throws an exception.

    To avoid this situation, I changed my code to this:

    def checkIsKaprekar( num ):
    string_num = str(num**2)
    left_string = string_num[:len(string_num)//2]
    right_string = string_num[len(string_num)//2:]
    left_num = int(left_string) if left_string != '' else 0
    right_num = int(right_string) if right_string != '' else 0
    if num == left_num + right_num:
    return True

    kaprekars = [ str(i) for i in range(int(input()),int(input())) if checkIsKaprekar(i) == True ]
    print (' '.join(kaprekars))


    But I don't like this code even though it does solve the purpose. How can I tweak my original code to produce the right output?

    Link to the question: https://www.hackerrank.com/challenges/kaprekar-numbers

    Is there any way I can specify a default value of 0 if the string is ''?

    Continue reading...

Compartilhe esta Página