The answer of the question this is marked duplicate of is wrong and does not satisfy my needs.
我的代码旨在从一系列数字中计算哈希值。在
矩阵形式的结构更容易理解。如果我有16个从29开始的数字,那么结构将是:(start=29,length=4)
29,30,31,32,
33,34,35,36,
37,38,39,40,
41、42、43、44
给定算法指定哈希将是以粗体显示的数字的异或:
29、30、31、32,//,
33,34,35,//,36,
37,38,//,39,40,
41,//,42,43,44
哈希=29^30^31^32^33^34^35^37^38^39
=54
我的代码是:
def answer(start, length):
val=0
c=0
for i in range(length):
for j in range(length):
if j < length-i:
val^=start+c
c+=1
return val
计算像answer(2000000000,10**4)
这样的大值所需的时间太多了。在
限制条件:
当前计算测试参数(我不知道)给我一个超时错误。在
如何提高代码的速度以获得更大的值?在
看起来您可以将内部循环替换为:
for j in range(length - i) val^=start+c c+=1 c+=i
当我变大的时候,这样可以节省一些时间恐怕我现在无法测试,对不起!在
恐怕,用你在
answer(2000000000,10**4)
中的输入,你永远无法“及时”完成。在通过改进内部循环,不必每次都更新},这样可以显著提高速度:
c
变量,并使用xrange
而不是{探查器显示
^{pr2}$answer_fast
的速度大约是后者的两倍:但是如果你想要大提速(magnitute命令),你应该考虑在Cython中重写你的函数。在
以下是“cythonized”版本:
在与上述相同的输入参数下,用时不到200毫秒,而不是20秒以上,这是100倍的加速。在
输入58毫秒:
在Python fast XOR over range algorithm的可接受答案中,存在一个缺陷:在进行异或计算之前,{a1}的递减需要在之前完成。这是一个修复过的版本,以及一个
assert
测试来验证它是否给出了与朴素算法相同的结果。在在
^{pr2}$start
和length
的范围内,gen_nums
大约比answer
快5倍,但我们可以通过消除这些函数调用使其速度再快一倍(即大约是answer
的10倍):正如Mirek Opoka在评论中提到的,},它更快,因为按位运算比执行整数除法和丢弃商更快。所以我们可以用
% 4
相当于{相关问题 更多 >
编程相关推荐