Skip to content
Create a gist now

Instantly share code, notes, and snippets.

anonymous /

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Generating Kaprekar's constants in Python using map, reduce, and filter .... I know ...
#1. Take any four-digit number, using at least two different digits. (Leading zeros are allowed.)
#2. Arrange the digits in ascending and then in descending order to get two four-digit numbers, adding leading zeros if necessary.
#3. Subtract the smaller number from the bigger number.
#4. Go back to step 2.
#The above process, known as Kaprekar's routine, will always reach 6174 in at most 7 iterations.[4] Once 6174 is reached,
#the process will continue yielding 7641 – 1467 = 6174. For example, choose 3524:
#5432 – 2345 = 3087
#8730 – 0378 = 8352
#8532 – 2358 = 6174
# This program emits the number of steps it takes to reach either 0 or 6174.
DIGITS = map(lambda x: map(lambda x: x, str(x).zfill(4)), range(10000))
def kaprekar(x, y=0):
if int(''.join(x)) == 6174:
print y
elif int(''.join(x)) == 0:
print y
x = map(lambda x: x, str(int(''.join(sorted(x, reverse=True))) - int(''.join(sorted(x)))))
y += 1
if __name__ == '__main__':
for i in DIGITS:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.