【发布时间】:2016-08-16 08:27:34
【问题描述】:
我目前有 6 个单独的 for 循环,它们遍历一个数字列表,以匹配较大序列中的特定数字序列,并像这样替换它们:
[...0,1,0...] => [...0,0,0...]
[...0,1,1,0...] => [...0,0,0,0...]
[...0,1,1,1,0...] => [...0,0,0,0,0...]
还有它们的逆:
[...1,0,1...] => [...1,1,1...]
[...1,0,0,1...] => [...1,1,1,1...]
[...1,0,0,0,1...] => [...1,1,1,1,1...]
我现有的代码是这样的:
for i in range(len(output_array)-2):
if output_array[i] == 0 and output_array[i+1] == 1 and output_array[i+2] == 0:
output_array[i+1] = 0
for i in range(len(output_array)-3):
if output_array[i] == 0 and output_array[i+1] == 1 and output_array[i+2] == 1 and output_array[i+3] == 0:
output_array[i+1], output_array[i+2] = 0
总的来说,我使用蛮力检查对相同的 output_array 进行了 6 次迭代。有更快的方法吗?
【问题讨论】:
-
您的问题不清楚。分享一些代码和输入输出示例
-
关于时间复杂度,我将从
timeit模块开始测量不同的实现。如果您需要有关函数花费最多时间的更多详细信息,请使用profiler。理论复杂性通常不是一个好的指南,因为它在很大程度上取决于假设的实现及其复杂性。 Python 的内置数据结构经过高度优化,可能使用与您想象的完全不同的实现。 -
你能补充一些例子吗?例如,
01011010应该变成什么?是00011110吗?
标签: python arrays list design-patterns iterator