如何用程序得到一组数字的动态规律,前提已知该规律只有加法。
例如:1, 2, 3, 11, 12, 13, 21, 22, 23, 31, 32, 33, 41, 27, 37, 47, 67
可直观的发现这几组规律: [1, 2, 3], [11, 12, 13], [21, 22, 23], [31, 32, 33] 和 [27], [37], [47]
下面用代码实现:
a = [1,2,3,11,12,13,21,22,23,31,32,33,41,27,37,47,67]
data = []
for i in range(1,len(a)):
data.append( a[i]-a[i-1] )
for pos in range(1, len(data)//3):
for i in range(len(data)-pos):
if data[i] == data[i+pos]:
getp = True
p = [a[i:i+pos]]
r = 1
while r < (len(data)-i)//pos:
for j in range(pos):
if data[i+j] != data[i+pos*r+j]:
getp = False
break
if not getp:
break
else:
p.append(a[i+pos*r :i+pos*r +pos])
r += 1
if len(p) > 1:
print(p)
输出:
[[1], [2]]
[[11], [12]]
[[21], [22]]
[[31], [32]]
[[27], [37]]
[[1, 2, 3], [11, 12, 13], [21, 22, 23], [31, 32, 33]]
[[2, 3, 11], [12, 13, 21], [22, 23, 31]]
[[3, 11, 12], [13, 21, 22], [23, 31, 32]]
[[11, 12, 13], [21, 22, 23], [31, 32, 33]]
[[12, 13, 21], [22, 23, 31]]
[[13, 21, 22], [23, 31, 32]]
[[21, 22, 23], [31, 32, 33]]
该方法可以用来检测信号周期