Check if two variables have values โ€‹โ€‹from two different sets, DRY method

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 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'} 

it really returns False if they both have values โ€‹โ€‹in L,R or U,D and True otherwise. However, I find it multiple. Some suggestions for more DRY suitable?

+6
source share
2 answers

If you know that there are only two sets and that your values โ€‹โ€‹should be in one or the other, then you can simplify this:

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

Explanation:

  • If d is in set 1 and newd is in set 2, both sides == are True , so the expression returns True .
  • If d is in set 2 and newd is in set 1, both sides == are False , so the expression returns True .
  • If they are in the same set, one side == will return False , and the other True , so the result of the expression will be False .
+4
source

What about:

 In [8]: dmap = {'L':0, 'R':0, 'U':1, 'D':1} In [9]: dmap[d] != dmap[newd] Out[9]: False 
0
source

Source: https://habr.com/ru/post/899542/


All Articles