披露:这是作业帮助
我希望在给定位置i找到一个整数,同时重复构造并添加一个整数序列,最好具有良好的运行时间和性能。
答案 0 :(得分:1)
你在的每次迭代中从1重建子序列,而不是简单地保留序列并在下一次迭代中添加下一个数字,然后 extend 主要列表。
此外,您应该将str.join
推迟到 while 之后,而不是在每次迭代时构建字符串:
from itertools import count
def give_output(digitPos):
c = count(1)
l, lst = [], []
while len(lst) <= digitPos:
l.append(next(c)) # update previous sub-sequence
lst.extend(l)
return int(''.join(map(str, lst))[digitPos-1])
时序:
In [10]: %%timeit
...: giveOutput(500)
...:
1000 loops, best of 3: 219 µs per loop
In [11]: %%timeit
...: give_output(500)
...:
10000 loops, best of 3: 126 µs per loop
大约一半的时间!
如果你使用div-mod方法选择 i 项而不是构建一个大字符串,你甚至可以做得更好;我会留给你的。
答案 1 :(得分:0)
事实上,将列表和索引移到函数外部可能会更好地缓存结果:
list1 = []
i = 2
def giveOutput():
global list1
global i
digitPos = int(input())
while len(list1) <= digitPos:
list1.extend(list(map(int, ''.join(map(str, range(1, i))))))
i = i + 1
print(list1[digitPos -1])
当你获得一些测试用例时,这才真正有效。
更新:(感谢摩西关于构建字符串的想法)
实际上你的列表可能只是一个字符串:
all_digits = ''
digits_up_to_i = ''
i = 1
def giveOutput():
global all_digits
global digits_up_to_i
global i
digitPos = int(input())
while len(all_digits) <= digitPos:
digits_up_to_i += str(i)
all_digits += digits_up_to_i
i = i + 1
print(all_digits[digitPos -1])