
Kaprekar's algorithm

Let's take a random positive integer (e.g. 5914) and apply the Kaprekar's routine to it: At first, you create two new integers by ordering the digits in descending (9541) and ascending order (1459). Then you subtract the smaller from the greater number (9541 − 1459 = 8082). Repeat this procedure for the new number 8082.
Applying the Kaprekar's algorithm to any positive integer can result in three cases:
- A constant integer is reached
For 5914, the number sequence is: 5914, 8082, 8532, 6174, 6174, 6174, …
Thus, 6174 is the Kaprekar's constant corresponding to 5914. - A cycle of integers is reached
Example: 48, 36, 27, 45, 09, 81, 63, 27, 45, 09, 81, 63, 27, 45, 09, 81, 63, …
(Two different colors are used to highlight the Kaprekar's circle 27, 45, 09, 81, 63) - Zero is reached
Even though technically zero is also a constant (e.g. 7, 0, 0, 0, …), mathematicians don't consider zero to be a Kaprekar constant.
You might have noticed, that leading zeros can play an important role: in cycle 27, 45, 09, 81, 63, the nine must be treated as 09, not just 9. For any intermediate result, consider filling up with leading zeros to the total number of digits of the input integer.
Input: A positive integer n (0 ≤ n ≤ 999.999)
Output: A tuple consisting of three values:
- An integer which should be either the Kaprekar's constant to n, or (in case of a cycle) the first number of a
Kaprekar's cycle that is entered from n.
Note for clarification: Even though both integers 48 and 92 lead to the same circle (i.e. 27, 45, 09, 81, 63), both integers enter this circle at different numbers. Thus, your function should return 27 (for n = 48) and 63 for n = 92. - The number of Kaprekar operations that must be applied to n until a constant or a cycle is reached. If n is already a Kaprekar constant (or a number from a Kaprekar cycle), this should be counted as zero operations.
- A Boolean or None stating, which case have occurred for n: True for case A, False for case B, None for case C.
Examples:
assert kaprekar_algorithm(5914) == (6174, 3, True) assert kaprekar_algorithm(6174) == (6174, 0, True) assert kaprekar_algorithm(48) == (27, 2, False) assert kaprekar_algorithm(27) == (27, 0, False) assert kaprekar_algorithm(45) == (45, 0, False) assert kaprekar_algorithm(111) == (0, 1, None) assert kaprekar_algorithm(9) == (0, 1, None)