Kaprekar Constant | This function checks validity of kaprekar ' s ▁ constant . ▁ It ▁ returns ▁ kaprekar ' s constant for any four digit number " n " such that all digits of n are not same . ; Store current n as previous number ; Get four digits of given number ; Sort all four dgits in ascending order And giet in the form of number " asc " ; Get all four dgits in descending order in the form of number " desc " ; Get the difference of two numbers ; If difference is same as previous , we have reached kaprekar 's constant ; Else recur ; A wrapper over kaprekarRec ( ) ; Trying few four digit numbers , we always get 6174
def kaprekarRec ( n , prev ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT prev = n ; NEW_LINE digits = [ 0 ] * 4 ; NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT digits [ i ] = n % 10 ; NEW_LINE n = int ( n / 10 ) ; NEW_LINE DEDENT digits . sort ( ) ; NEW_LINE asc = 0 ; NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT asc = asc * 10 + digits [ i ] ; NEW_LINE DEDENT digits . sort ( ) ; NEW_LINE desc = 0 ; NEW_LINE for i in range ( 3 , - 1 , - 1 ) : NEW_LINE INDENT desc = desc * 10 + digits [ i ] ; NEW_LINE DEDENT diff = abs ( asc - desc ) ; NEW_LINE if ( diff == prev ) : NEW_LINE INDENT return diff ; NEW_LINE DEDENT return kaprekarRec ( diff , prev ) ; NEW_LINE DEDENT def kaprekar ( n ) : NEW_LINE INDENT rev = 0 ; NEW_LINE return kaprekarRec ( n , rev ) ; NEW_LINE DEDENT print ( kaprekar ( 1000 ) ) ; NEW_LINE print ( kaprekar ( 1112 ) ) ; NEW_LINE print ( kaprekar ( 9812 ) ) ; NEW_LINE