Created
August 23, 2010 01:39
-
-
Save dwf/544590 to your computer and use it in GitHub Desktop.
Messing around with Kaprekar's procedure.
This file contains hidden or 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
| def kaprekar(s, t=4): | |
| """ | |
| Demonstrate Kaprekar's procedure and its convergence to Kaprekar's constant. | |
| """ | |
| s = str(s) | |
| # t = 3 or 4 will converge; otherwise all bets are off. | |
| assert len(s) <= t | |
| if len(s) < t: | |
| s = ('0' * (t - len(s))) + s | |
| print s | |
| old = None | |
| new = int(''.join(sorted(s))[::-1]) - int(''.join(sorted(s))) | |
| while old != new: | |
| old = new | |
| s = str(new) | |
| if len(s) < t: | |
| s = ('0' * (t - len(s))) + s | |
| print s | |
| new = int(''.join(sorted(s))[::-1]) - int(''.join(sorted(s))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment