Rearranging the problem

The naive use of the product() function to compare all pixels and all colors was a bad idea. There are 10 million pixels, but only 2,00,000 unique colors. When mapping the source colors to target colors, we only have to save 2,00,000 values in a simple map.

We'll approach it as follows:

  1. Compute the source to target color mapping. In this case, let's use 3-bit color values as output. Each R, G, and B value comes from the eight values in the range(0,256,32) method. We can use this expression to enumerate all the output colors:
product(range(0,256,32), range(0,256,32), range(0,256,32))  
  1. We can then compute the Euclidean distance to the nearest color in our source palette, doing just 68,096 calculations. This takes ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.