Skip to content

Instantly share code, notes, and snippets.

@shreyshahi
Created February 6, 2025 03:44
Show Gist options
  • Select an option

  • Save shreyshahi/3e5349de06b90618f4d0aa2518ce19a6 to your computer and use it in GitHub Desktop.

Select an option

Save shreyshahi/3e5349de06b90618f4d0aa2518ce19a6 to your computer and use it in GitHub Desktop.
def number_difference(num):
# Convert number to string and pad with zeros if needed
num_str = str(num).zfill(4)
# Convert to list of digits and sort
digits = list(num_str)
# Create ascending and descending numbers
ascending = int(''.join(sorted(digits)))
descending = int(''.join(sorted(digits, reverse=True)))
# Return difference
return descending - ascending
# Loop through all 4 digit numbers
for num in range(1000, 10000):
difference = number_difference(num)
if difference == num:
print(f"Found number: {num}")
# Let's also show the calculation for verification
num_str = str(num).zfill(4)
ascending = int(''.join(sorted(list(num_str))))
descending = int(''.join(sorted(list(num_str), reverse=True)))
print(f" {descending} - {ascending} = {difference}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment