Created
December 29, 2010 13:15
-
-
Save anonymous/758525 to your computer and use it in GitHub Desktop.
Generating Kaprekar's constants in Python using map, reduce, and filter .... I know ...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
#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 | |
else: | |
x = map(lambda x: x, str(int(''.join(sorted(x, reverse=True))) - int(''.join(sorted(x))))) | |
y += 1 | |
kaprekar(x,y) | |
if __name__ == '__main__': | |
for i in DIGITS: | |
kaprekar(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment