灵光一闪,得到这一句:
all(map(lambda x:x==-1, series[-i:-mid] * series[-mid:])) # 对折,相乘,全是-1
爽到死!
完整代码如下:
import numpy as np
import matplotlib.pyplot as plt
# 函数:返回数组尾部对称长度
def symmetry(series):
for i in range(50, 0, -2):
mid = i // 2
is_symmetry = all(map(lambda x:x==-1, series[-i:-mid][::-1] * series[-mid:])) # 对折,相乘,全是-1
if is_symmetry:
return i
return 0
# 计算对称长度
series = np.random.choice([-1, 1], 100)
print(symmetry(series))
# 作图验证
fig, axes = plt.subplots(1, 1, sharex=True)
axes.plot(np.cumsum(series), 'rd-')
plt.show()
效果图