]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-42452: Improve colorsys.rgb_to_hls code (GH-23306)
authorJulien Jerphanion <git@jjerphan.xyz>
Sat, 28 Nov 2020 07:11:19 +0000 (07:11 +0000)
committerGitHub <noreply@github.com>
Sat, 28 Nov 2020 07:11:19 +0000 (02:11 -0500)
Cache repeated sum and difference to make code slightly faster and easier to read.

Lib/colorsys.py

index b93e3844067e4e55e0cc227b7f2f05e013724ab0..0f52512a67d87c571835467b411ec8ec4e691230 100644 (file)
@@ -75,17 +75,18 @@ def yiq_to_rgb(y, i, q):
 def rgb_to_hls(r, g, b):
     maxc = max(r, g, b)
     minc = min(r, g, b)
-    # XXX Can optimize (maxc+minc) and (maxc-minc)
-    l = (minc+maxc)/2.0
+    sumc = (maxc+minc)
+    rangec = (maxc-minc)
+    l = sumc/2.0
     if minc == maxc:
         return 0.0, l, 0.0
     if l <= 0.5:
-        s = (maxc-minc) / (maxc+minc)
+        s = rangec / sumc
     else:
-        s = (maxc-minc) / (2.0-maxc-minc)
-    rc = (maxc-r) / (maxc-minc)
-    gc = (maxc-g) / (maxc-minc)
-    bc = (maxc-b) / (maxc-minc)
+        s = rangec / (2.0-sumc)
+    rc = (maxc-r) / rangec
+    gc = (maxc-g) / rangec
+    bc = (maxc-b) / rangec
     if r == maxc:
         h = bc-gc
     elif g == maxc: