#!/usr/local/bin/python3
# Written by JD Baldwin Sep 2019 -- a translation of my own
# Perl code for this purpose.
#
# Just a simple demo of walking from any four-digit number (not with
# all the same digits) to Kaprekar's constant. I was a little
# surprised that I couldn't find sample code to do it, so I wrote
# it in Perl. I created a Python version after receiving two email
# requests for same.
#
# Email @ panix.com with questions or comments.
import sys # for argument parsing
def nextkap( k, i ):
# Takes string k (guaranteed to be a 4-digit number), integer i
#
# Returns the next number (as a string) in the Kaprekar sequence:
# (k, digits sorted high to low) - (k, digits sorted low to high)
#
# i is the iteration number, only provided to print a trace
k_int_1 = int( ''.join(sorted(k))[::-1] ) # sorted digits high-to-low
k_int_2 = int( ''.join(sorted(k)) ) # sorted digits low-to-high
k_int_next = k_int_1 - k_int_2 # next in sequence
k_next = "%04d" % k_int_next # string version of
# next in sequence
print( " Iteration #%d: %04d - %04d == %s" %
( i, k_int_1, k_int_2, k_next ) )
return( k_next ) # returns the *string* version
try: # make sure there is an argument
assert( len( sys.argv ) == 2 ) # and only exactly one argument
nstr = sys.argv[1]
except:
print( "Usage: %s " % sys.argv[0] )
exit( -1 )
try: # make sure the argument has <= four characters (1-, 2- and
# 3-digit numbers are OK; we'll pad those with zeroes)
n = int( nstr )
assert( len( nstr ) <= 4 )
except:
print( "%s is not a four-digit number" % nstr )
exit( -1 )
leading_zeroes = '0' * ( 4 - ( len( nstr ) ) )
nstr = leading_zeroes + nstr
#
if nstr[0] == nstr[1] and nstr[1] == nstr[2] and nstr[2] == nstr[3]:
print( "Cannot start from a \"repdigits\" number." )
exit( -1 )
print( "Starting with %s ..." % nstr )
i = 1
while True: # don't test for 6174 because we have to go through the
# first iteration for that number
nstr = nextkap( nstr, i )
i += 1
if nstr == '6174':
break
# This will always be 6174:
print( "... reaching %s" % nstr )