Tuesday, July 19, 2022

[FIXED] How to compare integers with accuracy in Python?

Issue

I have a tuple for color. For example, (218, 174, 84). The task is to increase each red, green and blue value by some increment and then compare it with an accuracy 1. How can I do this in Pythonic way? Do you know best practices?

Color: (218, 174, 84) Increment: 5

For red value 222, 223, 224 is legal. Green: 178, 179, 180, Blue: 88, 89, 90.


Solution

def valid_color(orig_color, new_color, increment):
    return all(c1 + increment - 1 <= c2 <= c1 + increment + 1 for c1, c2 in zip(orig_color, new_color))

Use zip() to pair up the components of the original color and the color you're comparing with. Then use comparison operators to test that each component is valid.



Answered By - Barmar
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.