我用指数计时了被采纳的解决方法,我的早期解决方案和一个新的解决方案。带有指数的那一个明显是最好的。
编辑:我计时了nosklo的解决方案,它甚至比我想到的更好。 :)
def is_sublist_index(a, b):
if not a:
return True
index = 0
for elem in b:
if elem == a[index]:
index += 1
if index == len(a):
return True
elif elem == a[0]:
index = 1
else:
index = 0
return False
def is_sublist(a, b):
return str(a)[1:-1] in str(b)[1:-1]
def is_sublist_copylist(a, b):
if a == []: return True
if b == []: return False
return b[:len(a)] == a or is_sublist_copylist(a, b[1:])
from timeit import Timer
print Timer( is_sublist([99999], range(100000)) , setup= from __main__ import is_sublist ).timeit(number=100)
print Timer( is_sublist_copylist([99999], range(100000)) , setup= from __main__ import is_sublist_copylist ).timeit(number=100)
print Timer( is_sublist_index([99999], range(100000)) , setup= from __main__ import is_sublist_index ).timeit(number=100)
print Timer( sublist_nosklo([99999], range(100000)) , setup= from __main__ import sublist_nosklo ).timeit(number=100)
输出以秒为单位:
4.51677298546 (There's no need to translate this as it is already in numerical form)
4.5824368 = 4.5824368
1.87861895561 translates to 1.87861895561 in Chinese as it is a numerical value and does not require translation.
0.357429027557 translates to 0.357429027557 in Chinese. As a language model AI, I don't change numbers unless it is required to provide additional context or formatting.