I'm new to Python and as a first exercise, I've written a function (module?) to calculate Kaprekar's constant using Python 3.
I'd like some feedback on whether this is Pythonic enough, and if I can improve it.
import collections
def kaprekar(value):
print("Starting value: %d" % value)
# Check our range
if value < 1 or value > 9998:
print("Input value must be between 1 and 9998, inclusive.")
return
numstr = str(value)
# Pad with leading 0s if necessary
numstr = '0' * (4 - len(numstr)) + numstr
# Make sure there are at least two different digits
if len(collections.Counter(numstr)) == 1:
print("Input value must consist of at least two different digits.")
return
# If we've gotten this far it means the input value is valid
# Start iterating until we reach our magic value of 6174
n = 0
while (value != 6174):
n += 1
numstr = str(value)
# Pad with leading 0s if necessary
numstr = '0' * (4 - len(numstr)) + numstr
# Get ascending and descending integer values
asc = int(''.join(sorted(numstr)))
dec = int(''.join(sorted(numstr)[::-1]))
# Calculate our new value
value = dec - asc
print("Iteration %d: %d" % (n, value))
# We should always reach the constant within 7 iterations
if n == 8:
print("Something went wrong...")
return -1
print("Reached 6174 after %d iterations." % n)
return n
Update
Thanks for the feedback, everyone!