(lambda x, y: x ^ y)(7, 10)
from operator import xor
xor(7, 10)
> Clearly the second option is more readable.Clearly, the readable option here is ”7 ^ 10”. The examples are a bit contrived, so readability can’t really be gauged from them.
(lambda x, y: x ^ y)(7, 10)
from operator import xor
xor(7, 10)
> Clearly the second option is more readable.Clearly, the readable option here is ”7 ^ 10”. The examples are a bit contrived, so readability can’t really be gauged from them.
If you want to do a parity check on a string:
parity = reduce(xor, map(ord, str))%2
Except Python3 took reduce away in favor of more boilerplate. And yes, there are multiple alternative implementations of the above."% 2" will not calculate the parity of the reduced value; it just extracts the least significant bit.
I'm guessing the last one since that's what fits your LSB comment(when using 'evenness' not 'oddness'). But in that case I'm not sure your example is doing, my python might be too rusty but is it something like: get the unicode representation(int) of each character in a string, xor the results and get the LSB?
But, the more useful concept is parity for error detection, which my example clearly fails at.
https://en.wikipedia.org/wiki/Parity_bit
https://en.wikipedia.org/wiki/Parity_(mathematics)
"parity check on a string" tends toward the former interpretation of "parity". You don't do parity checks by looking at only the least significant bit of every code word.
If the examples don’t show cases where the feature even arguably is the best option, they’re bad examples of the feature. I don’t think that’s nitpicking.
#this used to be y = 2 * x + 1 until I read a sweet blog
y = operator.add(1, operator.mul(2, x))
I really don't see any danger of that, myself.You can import functools.reduce to get it back but maybe thats what you meant with more boilerplate