Skip to content

Instantly share code, notes, and snippets.

@Fortyseven
Created January 21, 2025 08:08
Show Gist options
  • Save Fortyseven/e6fa7aa2255452332310dc59b232ebb5 to your computer and use it in GitHub Desktop.
Save Fortyseven/e6fa7aa2255452332310dc59b232ebb5 to your computer and use it in GitHub Desktop.
hex_color_similarity generated by Deepseek-R1
import math
def hex_color_similarity(hex1, hex2):
# Remove any leading '#' characters
c1 = hex1.lstrip('#')
c2 = hex2.lstrip('#')
# Ensure that each color is exactly 6 characters long
if len(c1) != 6 or len(c2) != 6:
raise ValueError("Hex color must be 6 characters long.")
try:
# Split into R, G, B components and convert to integers (0-255)
r1 = int(c1[0:2], 16)
g1 = int(c1[2:4], 16)
b1 = int(c1[4:6], 16)
r2 = int(c2[0:2], 16)
g2 = int(c2[2:4], 16)
b2 = int(c2[4:6], 16)
except ValueError:
raise ValueError("Invalid hexadecimal digits.")
# Compute the absolute differences for each component
dr = abs(r1 - r2)
dg = abs(g1 - g2)
db = abs(b1 - b2)
# Calculate Euclidean distance squared to avoid repeated sqrt operations
distance_sq = dr**2 + dg**2 + db**2
distance = math.sqrt(distance_sq)
max_distance = 255 * math.sqrt(3) # Maximum possible Euclidean distance
similarity = 1 - (distance / max_distance)
return round(similarity, 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment