Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the missing value more concisely?

The following code checks if x and y are distinct values (the variables x, y, z can only have values a, b, or c) and if so, sets z to the third character:

if x == 'a' and y == 'b' or x == 'b' and y == 'a':     z = 'c' elif x == 'b' and y == 'c' or x == 'c' and y == 'b':     z = 'a' elif x == 'a' and y == 'c' or x == 'c' and y == 'a':     z = 'b' 

Is is possible to do this in a more, concise, readable and efficient way?

like image 523
Bunny Rabbit Avatar asked Jan 09 '12 17:01

Bunny Rabbit


Video Answer


2 Answers

z = (set(("a", "b", "c")) - set((x, y))).pop() 

I am assuming that one of the three cases in your code holds. If this is the case, the set set(("a", "b", "c")) - set((x, y)) will consist of a single element, which is returned by pop().

Edit: As suggested by Raymond Hettinger in the comments, you could also use tuple unpacking to extract the single element from the set:

z, = set(("a", "b", "c")) - set((x, y)) 
like image 90
Sven Marnach Avatar answered Sep 28 '22 11:09

Sven Marnach


The strip method is another option that runs quickly for me:

z = 'abc'.strip(x+y) if x!=y else None 
like image 45
chepner Avatar answered Sep 28 '22 11:09

chepner