human
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"
How can the above be solved in Python?
assistant
#Here is code to kaprekar Constant and the other steps required.
 def kaprekarRec ( n , prev ) :
	if ( n == 0 ) :
		return 0 ;
	prev = n ;
	digits = [ 0 ] * 4 ;
	for i in range ( 4 ) :
		digits [ i ] = n % 10 ;
		n = int ( n / 10 ) ;
	digits . sort ( ) ;
	asc = 0 ;
	for i in range ( 4 ) :
		asc = asc * 10 + digits [ i ] ;
	digits . sort ( ) ;
	desc = 0 ;
	for i in range ( 3 , - 1 , - 1 ) :
		desc = desc * 10 + digits [ i ] ;
	diff = abs ( asc - desc ) ;
	if ( diff == prev ) :
		return diff ;
	return kaprekarRec ( diff , prev ) ;
def kaprekar ( n ) :
	rev = 0 ;
	return kaprekarRec ( n , rev ) ;
print ( kaprekar ( 1000 ) ) ;
print ( kaprekar ( 1112 ) ) ;
print ( kaprekar ( 9812 ) ) ;