【发布时间】:2017-01-11 02:53:15
【问题描述】:
当我在谷歌上搜索有关 Python 列表理解的信息时,我收到了一个 google foobar 挑战,过去几天我一直在慢慢研究它以获得乐趣。最新挑战:
实际上要求生成一个 ID 列表,忽略每一新行中不断增加的数字,直到剩下一个 ID。然后你应该对 ID 进行 XOR(^) 以产生校验和。我创建了一个输出正确答案的工作程序,但是它不足以在分配的时间内通过所有测试用例(通过 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)
【问题讨论】:
-
你有两个内部循环。尝试摆脱它们。