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)
總結
以上是生活随笔為你收集整理的python中异或运算_python – 基于ID列表有效计算XOR(^)校验和的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: i12蓝牙耳机使用说明书图片_飞利浦SH
- 下一篇: 环信SDK 踩坑记webIM篇(二)