Last active
September 5, 2021 05:09
-
-
Save JosephTLyons/c28b2bb94f9e8fd9c263fe0f04fe1839 to your computer and use it in GitHub Desktop.
Exploring Kaprekar's constant
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
| import random | |
| from typing import Optional | |
| def main() -> None: | |
| run_number: int = 0 | |
| run_amount: int = 10_000 | |
| count_total: int = 0 | |
| while run_number < run_amount: | |
| count: Optional[int] = kaprekar() | |
| if count: | |
| count_total += count | |
| run_number += 1 | |
| average: float = count_total / run_amount | |
| print(average) | |
| print(average <= 7) | |
| def kaprekar() -> Optional[int]: | |
| count: int = 0 | |
| number: int = random.randint(1000, 9999) | |
| KAPREKARS_CONSTANT: int = 6174 | |
| while number != KAPREKARS_CONSTANT: | |
| digit_strings: list[str] = [digit for digit in str(number)] | |
| if len(set(digit_strings)) == 1: | |
| # In this case, the random number digits were all the same (Ex: 9999) | |
| # This will result in an infinite loop, so we should return and not count this run | |
| return None | |
| digit_strings_ascending: list[str] = sorted(digit_strings, key=int) | |
| digit_strings_descending: list[str] = list(reversed(digit_strings_ascending)) | |
| smallest_number: int = int("".join(digit_strings_ascending)) | |
| largest_number: int = int("".join(digit_strings_descending)) | |
| number = largest_number - smallest_number | |
| count += 1 | |
| assert(count <= 7) | |
| return count | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment