如何创建通过迭代运行的累积代码?

时间:2019-02-23 16:18:50

标签: python iteration

我正在尝试创建一个通过迭代运行的“累积”代码。通常,组合器采用2个参数,例如Combiner(x,y)返回一个函数,例如(x + y)和项决定了每个值的函数,例如term(x)给您x ^ 2意味着a的下一个值将是x ^ 2,next将是确定例如e之后的下一个值的函数。 x = x + 1。

我的代码有问题,因为在某些情况下它会运行不必要的附加循环(例如,空值必须是该循环在退出while循环之前要处理的最后一个值,例如

    AttributeError Traceback (most recent call last)
    <ipython-input-172-9812ddb325e6> in <module>()
    ----> 6     pred = pm.sample_posterior_predictive(trace_x, 100, model_x, size=30)

   .../python2.7/site-packages/pymc3/sampling.pyc in sample_posterior_predictive(trace, samples, model, vars, size, random_seed, progressbar)
       1128         for idx in indices:
       1129             if nchain > 1:
    -> 1130                 chain_idx, point_idx = np.divmod(idx, len_trace)
       1131                 param = trace._straces[chain_idx % nchain].point(point_idx)
       1132             else:

    AttributeError: 'module' object has no attribute 'divmod'

输入的示例为: accumulate_iter(lambda x,y:x y,1,lambda x:x x,1,lambda x:x + 1,5)

输出将为您:14400

1 个答案:

答案 0 :(得分:2)

def accumulate_iter(combiner, term, a, next, b):
    result = term(a)
    while a <= b:
        a = next(a)
        if a <= b:
            result = combiner(term(a), result)

    return result

print(accumulate_iter(lambda x, y: x * y, lambda x: x * x, 1, lambda x: x + 1, 5))

输出:

14400

您还可以完全摆脱额外的循环迭代,因此不需要额外的(x <= y)测试:

def accumulate_iter(combiner, term, a, next, b):
    result = term(a)
    a = next(a)
    while a <= b:
        result = combiner(term(a), result)
        a = next(a)

    return result

请注意,第二个版本更符合实际情况。循环“将事物组合”,这意味着您需要将两个事物组合在一起,但是每次迭代仅拾取一件新事物。因此,在处理第一个术语并越过它的循环之前有一个特殊情况很自然。