gpt4 book ai didi

python - 在 Python 3 中返回整数中最低有效位集的位置的最快方法是什么?

转载 作者:行者123 更新时间:2023-12-01 04:17:27 26 4
gpt4 key购买 nike

我很好奇在 Python 3 中返回整数中最低有效位集的位置的最快算法是什么。

Python 3 中有比这个更快的算法吗?有什么增强功能可以用来加快速度吗?

def lsb(n):
temp = n & -n
pos = -1
while temp:
temp >>= 1
pos += 1
return(pos)

最佳答案

总结一下,因为这是针对 python3 的,所以不是 return index of least significant bit in Python 的精确副本(尽管那里还有其他适用的答案,有些可能更好):

jcomeau@aspire:/tmp$ cat lsb.py 
#!/usr/bin/python3
import math, sys
def lsb0(n):
temp = n & -n
pos = -1
while temp:
temp >>= 1
pos += 1
return(pos)
def lsb1(n):
return int(math.log2(n & -n))
def lsb2(n):
return (n & -n).bit_length() - 1
if __name__ == '__main__':
algorithm = sys.argv[1]
lsb = eval('lsb{n}'.format(n = algorithm))
for n in range(1, 1000000):
#print(lsb(n))
lsb(n)

正如 aaron_world_traveler 观察到的,Mark Dickinson 的答案是最快的。

jcomeau@aspire:/tmp$ time lsb.py 0

real 0m2.506s
user 0m2.472s
sys 0m0.024s
jcomeau@aspire:/tmp$ time lsb.py 1

real 0m3.336s
user 0m3.284s
sys 0m0.040s
jcomeau@aspire:/tmp$ time lsb.py 2

real 0m1.646s
user 0m1.636s
sys 0m0.008s

关于python - 在 Python 3 中返回整数中最低有效位集的位置的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34166566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com