Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two variables have values from two different sets, the DRY way

I have a range of values (L,R,U,D) and two variables, d and newd, containing one of them. I need to check if d and newd are in the same subset (L,R or U,D) or not.
I know I can do this:

d in {'L','R'} and newd in {'U','D'} or d in {'U','D'} and newd in {'L','R'}

this indeed returns False if they both have values in L,R or U,D, and True otherwise. Still, I find it much reduntant. Some suggestions about a more DRY approach?

like image 719
etuardu Avatar asked Oct 18 '11 17:10

etuardu


People also ask

How do you know if two objects are the same reference?

Summary. The referential equality (using === , == or Object.is() ) determines whether the operands are the same object instance.

Can variables contain different values at different times?

A variable is a characteristic that can be measured and that can assume different values. Height, age, income, province or country of birth, grades obtained at school and type of housing are all examples of variables.

How do you check if two values are the same in Python?

Use the == operator to test if two variables are equal.

How do you test a variable against multiple values in Python?

To test multiple variables x , y , z against a value in Python, use the expression value in {x, y, z} . Checking membership in a set has constant runtime complexity. Thus, this is the most efficient way to test multiple variables against a value.


1 Answers

If you know that there are only two sets and that your values must be in one or the other, then you can simplify it to this:

(d in set1) == (newd in set2)

Explanation:

  • If d is in set 1 and newd is in set 2, both sides of the == are True, so the expression returns True.
  • If d is in set 2 and newd is in set 1, both sides of the == are False, so the expression returns True.
  • If they are in the same set, one side of the == will return False and the other True so the result of the expression will be False.
like image 110
Mark Byers Avatar answered Oct 12 '22 23:10

Mark Byers