python中异或运算_python – 基于ID列表有效计算XOR(^)校验和的方法

当谷歌搜索有关

Python列表理解的信息时,我获得了一个google foobar挑战,我在过去的几天里一直在慢慢地工作以获得乐趣.最新挑战:

有效地要求生成ID列表,忽略每个新行的增加数字,直到剩下一个ID.然后你应该XOR(^)ID来产生校验和.我创建了一个输出正确答案的工作程序,但是在分配的时间内传递所有测试用例(通过6/10)效率不高.长度为50,000应该在20秒内产生结果,但需要320.

有人可以引导我朝着正确的方向前进,但请不要为我做这件事,我很乐意用这个挑战推动自己.也许我可以实现一种数据结构或算法来加快计算时间?

代码背后的逻辑:

>首先,获取起始ID和长度

>生成ID列表,忽略每个新行中越来越多的ID,从忽略第一行的0开始.

>使用for循环对IDS列表中的所有数字进行异或

>答案以int形式返回

import timeit

def answer(start,length):

x = start

lengthmodified = length

answerlist = []

for i in range (0,lengthmodified): #Outter for loop runs an amount of times equal to the variable "length".

prestringresult = 0

templist = []

for y in range (x,x + length): #Fills list with ids for new line

templist.append(y)

for d in range (0,lengthmodified): #Ignores an id from each line, increasing by one with each line, and starting with 0 for the first

answerlist.append(templist[d])

lengthmodified -= 1

x += length

for n in answerlist: #XORs all of the numbers in the list via a loop and saves to prestringresult

prestringresult ^= n

stringresult = str(prestringresult)

answerlist = [] #Emptys list

answerlist.append(int(stringresult)) #Adds the result of XORing all of the numbers in the list to the answer list

#print(answerlist[0]) #Print statement allows value that's being returned to be checked, just uncomment it

return (answerlist[0]) #Returns Answer

#start = timeit.default_timer()

answer(17,4)

#stop = timeit.default_timer()

#print (stop - start)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值