生成序列的算法

2024-06-09 18:15:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个场景,给出两个数字。我不断地发现它们的平均值或某些函数达到了不同的水平。你知道吗

例如:

Input I = 2, 64
I1=2, 33=f(2,64), 64
I1=2, 33, 64
I2=2, 17=f(2,33), 33, 49=f(33,64), 64 
I2=2,17,33,49,64
I3=2,9=f(2,17),17,25=f(17,33),33,41=f(33,49),49,57=f(49,64),64
I3=2,9,17,25,33,41,49,57,64

在第一次迭代中,应用函数f(2,64)来查找中间值—在本例中为33。然后写出结果序列;现在是三个元素。下一步,将函数应用于(2,33)得到17,应用于(33,64)得到49。等等。–编辑Floris的帮助

有什么算法可以有效地进行编码吗?你知道吗


Tags: 函数算法元素编辑input场景水平序列
1条回答
网友
1楼 · 发布于 2024-06-09 18:15:05
from itertools import izip_longest

def apply_pairwise(lst, f, loops=1):
    if loops == 0:
        return lst
    new_lst = [f(a,b) for a,b in zip(lst, lst[1:])]
    next_lst = [e for t in izip_longest(lst, new_lst) for e in t if e]
    return apply_pairwise(next_lst, f, loops-1)

然后可以指定要使用的两两函数,该函数取两个值

>>> apply_pairwise([2, 64], lambda x,y: (x+y)/2.0, 3)
[2, 9.75, 17.5, 25.25, 33.0, 40.75, 48.5, 56.25, 64]

相关问题 更多 >