-2

I have a scenario, where two numbers are given. And I have continually find the average/or some function of them up to different levels.

For example:

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

On the first iteration, you apply a function f(2,64) to find an intermediate value - in this case, 33. You then write out the resulting series; now three elements long. On the next pass, you apply your function to (2,33) to give 17, to (33,64) to give 49. Etcetera. – Edit help from Floris

Any algorithm to code this computationally effectively?

4

1 回答 1

1
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)

You can then specify whatever pairwise function to use which takes two values,

>>> 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]
于 2013-05-22T06:45:20.383 回答