我想要一个方法来获取下一个可能的元素作为列表的延续,遵循列表中的模式。
说,有一个列表 ls,
ls = [1,2,2,3,2,2,1,2,2,3]
我想获取列表的下一个可能元素。在这种情况下,“2”。
“需要人工智能”的建议当然是愚蠢的。但是你的问题陈述不清楚。您作为示例提供的系列后面可以跟一个 2,但其他解决方案也是可能的,这里是 OEIS 网站 上的一些示例。
但是,假设您正在寻找平凡的扩展算术级数(无限重复固定数量的简单算术步骤),这是一个解决方案:
def find_pattern(xs):
if len(xs) < 2:
return [0]
n = 1
while n < len(xs):
pattern = list(map(lambda x: x[1] - x[0], zip(xs[:n], xs[1:n + 1])))
for i, (x, y) in enumerate(zip(xs, xs[1:])):
if y - x != pattern[i % n]:
n = i + 1
break
else:
return pattern
sample = [1, 2, 2, 3, 2, 2, 1, 2, 2, 3]
pattern = find_pattern(sample)
print(pattern)
使用该示例模式,您可以扩展系列:
def extend_pattern(xs, pattern, n):
x = xs[0]
for i in range(n):
yield x
if i < len(xs) and xs[i] != x:
raise ValueError(f'The series {xs} does not match the pattern {pattern} at index {i}.')
x = x + pattern[i % len(pattern)]
print(list(extend_pattern(sample, pattern, 15)))
合并后,输出:
[1, 0, 1, -1, 0, -1]
[1, 2, 2, 3, 2, 2, 1, 2, 2, 3, 2, 2, 1, 2, 2]
然而,作为一个例子,这会变得非常错误:
sample = [2, 3, 5, 7, 11, 13, 17, 19]
pattern = find_pattern(sample)
print(pattern)
print(list(extend_pattern(sample, pattern, 15)))
结果:
[1, 2, 2, 4, 2, 4, 2]
[2, 3, 5, 7, 11, 13, 17, 19, 20, 22, 24, 28, 30, 34, 36]
对一个人来说,很明显 [2, 3, 5, 7, 11, 13, 17, 19]
是一个素数列表,但这当然不是函数找到的结果。
您可以在遍历列表时跟踪最短周期的长度。
cycle = 1
for i, x in enumerate(ls):
if x != ls[i % cycle]:
cycle = i + 1
print(ls[len(ls) % cycle]) # 2