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?
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))
The strip
method is another option that runs quickly for me:
z = 'abc'.strip(x+y) if x!=y else None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With