(split from To say weather number is odd or even)
alternative to modulus:
x = 3
if x & 1:
print('odd')
else:
print('even')
this directly grabs the last bit of the number in binary, just check whether it’s 0 or 1.
(split from To say weather number is odd or even)
alternative to modulus:
x = 3
if x & 1:
print('odd')
else:
print('even')
this directly grabs the last bit of the number in binary, just check whether it’s 0 or 1.
You can use division (x // 2 * 2
) and check if it equals x
. If it does, that means it’s an even number; otherwise, it’s odd. Also, you could compare the integer division of the number by 2 (x // 2
) with the result of integer division (x / 2
). If they are equal, the number is even; otherwise, it’s odd.
A more convoluted (but original) method would be like so:
div2 = lambda x: 1 in [x := abs(x)-2 for _ in range(abs(x)//2+2)]
print(div2(5))
It does not work for negative numbers. (Also, interesting use of the walrus operator)
oooohh did not know about that ill update it
EDIT: try now!
it does not really work for -2 < x < 2
Try now, itll work. I just updated the range
and yet, the speed benefit is not consistent. So, let’s consider the results which are both more frequent and more dramatic. For larger numbers, I find &
is slower than %
. For smaller numbers, &
wins. Python 3.12:
lol still doesnt work for -2 < x < 2
That is interesting.
One benefit of &
over %
is that it rejects all floats.
What about using bitwise
def is_even_bitwise_operator(number):
return (number & 1) == 0
I did say that in the original post.
Also, I prefer using not
over == 0
def is_even_bitwise_operator(number):
return not (number & 1)
what about…
div3 = lambda x: float(x//2) == x/2
div4 = lambda x: not x - x//2
div5 = lambda x: x-x//10 in (0, 2, 4, 6, 8. "Never", "Gonna", "Give", "You", "Up)
def div3(x): return x//2 != x/2
def div5(x): return x-(x//10*10) not in (0, 2, 4, 6, 8. "Never", "Gonna", "Give", "You", "Up)
I think div4
does not work, and I fixed div5
.
Uhh yeah no lol it’ll still syntax error
yeah I noticed that but forgot to fix it
the code was wrong though
check_even_odd = lambda x: "even" if str(x / 2)[-1] == "0" else "odd"