public
anonymous / Kaprekar.py
Last active

Generating Kaprekar's constants in Python using map, reduce, and filter .... I know ...

  • Download Gist
Kaprekar.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#!/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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.