当谷歌搜索有关
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)