+ 1
¿Par o impar? | Soluciones
Tengo la solución al Par o impar: https://code.sololearn.com/cBXHJz7EdGpP/?ref=app Pero queda muy raro, alguien tiene otra forma?
6 Respuestas
+ 1
Thanks Brian !!!
+ 7
Leonardo emiliano Netto barros your solution is very good.
Another way is to compare the lowest bit. If the bit=0, then it is even. If the bit=1, then it is odd. You can use the bitwise & operator to get the value of the lowest bit:
if a&1==0:
print("even")
else:
print("odd")
This is a much faster comparison than modulo (%).
+ 2
Евгений Python surprises me at every turn. My past timeit() tests in Python had shown that modulo was clearly slower. But I see your test, and now I know I had overgeneralized the conclusion.
In light of your reply, I investigated more deeply and learned that speed is significantly affected by the range of integer values on either side of the operators. In Python, Bitwise And (&) can be more vulnerable than Modulo (%) to slow down when the integers are stored in different numbers of bytes. There can be extra steps required to upscale one or the other value so that they match in size.
So Leonardo emiliano Netto barros, I backtrack my earlier claim. Now I would say % has a better chance of being faster than &. Though if it matters, do the timeit() test. You will get varied results on other CPUs, Python interpreters, and different data values.
+ 1
You're welcome!
+ 1
So, Leonardo emiliano Netto barros, just use modulo operator, it is not slower. And it's certainly not "much slower" :)
0
Brian Is it really so? My tests show that it's not the case. The compiled code for the `a%2` and the `a&2` differ only in one operation: BINARY_MODULO vs. BINARY_AND. And the modulo version runs faster. Which is in fact counterintuitive, I admit.
https://code.sololearn.com/cIt5wgUKNTzM/
```
Disassembly for modulo operator
1 0 LOAD_NAME 0 (a)
2 LOAD_CONST 0 (2)
4 BINARY_MODULO
6 PRINT_EXPR
8 LOAD_CONST 1 (None)
10 RETURN_VALUE
Disassembly for and operator
1 0 LOAD_NAME 0 (a)
2 LOAD_CONST 0 (2)
4 BINARY_AND
6 PRINT_EXPR
8 LOAD_CONST 1 (None)
10 RETURN_VALUE
Results for modulo operator:
min=0.07543 mean=0.0952 stdev=0.03257 median=0.07607
Results for 'bitwise and' operator:
min=0.1241 mean=0.1928 stdev=0.04994 median=0.1867
```