1+ """
2+ Kaprekar's Constant (6174)
3+
4+ Kaprekar's routine is an algorithm that, with a few exceptions, will eventually
5+ converge to the number 6174.
6+
7+ The routine is as follows:
8+ 1. Take any four-digit number, using at least two different digits.
9+ 2. Arrange the digits in descending and then in ascending order to get two
10+ four-digit numbers.
11+ 3. Subtract the smaller number from the bigger number.
12+ 4. Go back to step 2 and repeat.
13+ """
14+
15+ KAPREKARS_CONSTANT = 6174
16+
17+ def kaprekar_routine (n : int ) -> list [int ]:
18+ """
19+ Performs the Kaprekar routine and returns the sequence of numbers.
20+ >>> kaprekar_routine(3524)
21+ [3524, 3087, 8352, 6174]
22+ >>> kaprekar_routine(6174)
23+ [6174]
24+ """
25+ if not 1000 <= n <= 9999 :
26+ raise ValueError ("Input must be a four-digit number." )
27+ if len (set (str (n ).zfill (4 ))) < 2 :
28+ raise ValueError ("Input must have at least two different digits." )
29+
30+ sequence = [n ]
31+ while n != KAPREKARS_CONSTANT :
32+ s_num = str (n ).zfill (4 )
33+ desc_str = "" .join (sorted (s_num , reverse = True ))
34+ asc_str = "" .join (sorted (s_num ))
35+ n = int (desc_str ) - int (asc_str )
36+ sequence .append (n )
37+ return sequence
38+
39+ if __name__ == "__main__" :
40+ import doctest
41+ doctest .testmod ()
42+ try :
43+ num = int (input ("Enter a 4-digit number (with at least two different digits): " ))
44+ result_sequence = kaprekar_routine (num )
45+ print (f"Sequence: { ' -> ' .join (map (str , result_sequence ))} " )
46+ except ValueError as e :
47+ print (f"Error: { e } " )
0 commit comments