# Finding Kaprekar’s constant 6174 with Python

Numberphile once did a fascinating video about the number 6174. The video describes a simple, iterative algorithm which you can feed almost any 4-digit number, and within seven iterations it will always produce 6174. This number is known as Kaprekar’s constant, after the mathematician Kaprekar.

I thought this was so cool I wanted to try to implement the algorithm, which is known as Kaprekars routine, in Python.

My code:

``````KAPREKAR_CONSTANT = 6174

def kaprekar_map(nbr):
"""Return the Kaprekar mapping of nbr."""
parts = sorted("%04d" % nbr)
low, high = [int("".join(x)) for x in [parts, reversed(parts)]]
return high - low

def kaprekar_steps(nbr, verbose=False):
"""Return steps to reach 6174 from nbr, or -1 if impossible."""
maxsteps = 7
current = nbr
for step in range(maxsteps):
if current == KAPREKAR_CONSTANT:
return step # done
if current < 0:
return -1
previous, current = current, kaprekar_map(current)
if verbose:
print("%04d -> %04d" % (previous, current))
return -1
``````

So if you want to know the number of steps to 6174 for each number 0000-9999 you can do

``````[(x,kaprekar_steps(x)) for x in range(0,10000)]
``````

`kaprekar_steps` returns -1 if there is no path to 6174 from that number. This will happen for 0000, 1111, 2222, 3333, …, and so on. This is expected and explained in the video

If you call `kaprekar_steps` with `verbose=True` then you also get a printout showing every step of the way to 6174. For example, here’s the output from calling `kaprekar_steps(9,True)`:

``````0009 -> 8991
8991 -> 8082
8082 -> 8532
8532 -> 6174
4
``````