1
\$\begingroup\$

I have this piece of code where it based on this condition:

  1. Box Color can only be in red, white and black
  2. If the box's type is A then any color is allowed
  3. Box's type C is not allowed at all
  4. For the gift, only green and blue color is allowed and the size cannot be small
  5. Box and gift color cannot be same

views.py

    boxColor = ["red", "white", "black"]
    giftColor = ["green", "blue"]
    if box.color != gift.color:
        if gift.color in giftColor and gift.size != "small":
            if (box.type == "A") or (box.type != "C" and box.color in boxColor):
                return True
            else:
                return False
        else:
            return False
    else:
        return False    

Is there is a way to simplify my code that I can make this more efficient ?

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Review@SE. A return statement looks lacking context without a def, and the title doesn't follow site conventions: Please (re)visit How do I ask a Good Question? \$\endgroup\$
    – greybeard
    Commented Nov 6, 2021 at 13:10

1 Answer 1

1
\$\begingroup\$

Yes, this should be simplified. Prefer sets since you're doing membership checks, and write this as a boolean expression rather than a series of if checks with returns:

return (
    box.type != 'C'
    and (
        box.type == 'A'
        or box.color in {'red', 'white', 'black'}
    )
    and box.color != gift.color
    and gift.size != 'small'
    and gift.color in {'green', 'blue'}
)
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.