Skip to content

Instantly share code, notes, and snippets.

@caspercasanova
Created December 13, 2024 04:05
Show Gist options
  • Save caspercasanova/253f3c57a5d2165293af9e756104031a to your computer and use it in GitHub Desktop.
Save caspercasanova/253f3c57a5d2165293af9e756104031a to your computer and use it in GitHub Desktop.
def get_century_scale(current_number: float):
"""
Logic:
- For numbers with 1-digit: scale = 1 (e.g. 5)
- For numbers with 2-digits: scale = 10 (e.g. 50)
- For numbers with 3-digits: scale = 100 (e.g. 500)
- For numbers with 4-digits: scale = 100 (e.g. 5000)
- For numbers with 5-digits: scale = 1000 (e.g. 50,000)
- For numbers with 6-digits: scale = 10,000, and so forth.
Essentially:
- For numbers <= 999 (length ≤ 3): scale = 10^(length-1)
- For numbers ≥ 1000 (length > 3): scale = 10^(length-2)
"""
n_str = str(int(current_number))
length = len(n_str)
if length <= 3:
return 10 ** (length - 1)
else:
return 10 ** (length - 2)
def is_century_number(current_number: float):
# Check if the number is a century number
return current_number % get_century_scale(current_number) == 0
def get_closest_century_number(current_number: float):
# Calculate the scale (S)
scale = get_century_scale(current_number)
# Calculate the previous and next century numbers
prev_century = (current_number // scale) * scale
next_century = prev_century + scale
# Determine the closest century number
if abs(current_number - prev_century) >= abs(current_number - next_century):
return next_century
else:
return prev_century
def is_approaching_century_number(current_number: float, percent_threshold=5):
# Need to use the opposite scale for this kind of thing though.....
# Calculate the scale (S)
scale = get_century_scale(current_number)
closest_century_number = get_closest_century_number(current_number)
# Calculate the threshold as a fraction of the scale
threshold = scale * (percent_threshold / 100.0)
# Calculate the difference to the next century number
difference = abs(closest_century_number - current_number)
# Check if the difference is within the computed threshold
is_within_threshold = difference <= threshold
return is_within_threshold, closest_century_number, threshold, scale
is_century_number(33_000)
get_closest_century_number(9960)
is_approaching_century_number(99, 5)
# test 90-100, 110-100, 990-1000, 1010-1000, 1090-1100, 10999-11000, 9990-10000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment