在获得部分金额时屈服

时间:2013-11-27 14:07:24

标签: python python-2.7

我需要找到一组概率的子列表,这样子列表的负二进制对数之和为1(或刚刚超过1.0)。只要找到第一个这样的子列表就可以了。

为了做到这一点,我想我可以使用takewhile和生成器表达式,但我似乎无法让事情发生。

到目前为止,我有:

from itertools import takewhile
from numpy.random import dirichlet
from math import log

def partial_sums(iterable):
    total = 0
    for i in iterable:
        total += -1*log(i,2)
        yield total

probs = dirichlet([1]*1000).tolist()
probs = 10*probs
ps = partial_sums(probabilities)
s = takewhile(lambda x: x<1, sum(x for x in partial_sums(probs)))

这只是给我一个空列表。

编辑:如果我使用的是Python 3.我可以使用itertools.accumulate:

s = takewhile(lambda x: x<1, itertools.accumulate(math.log(x,2) for x in probs))

我正在寻找Python 2.7等价物。

编辑:我认为这是:

def partial_sums(iterable):
    total = 0
    for i in iterable:
        total += -1*log(i,2)
        if total >= 1.0:
            yield i

可行,但唉不行。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

from itertools import takewhile
from numpy.random import dirichlet
from math import log

def partial_sums(iterable):
    total = 0
    for i in iterable:
        total += i
        yield total

probs = dirichlet([1]*1000).tolist()
probs = 10*probs
s = takewhile(lambda x: x<1, partial_sums(-1*log(x,2) for x in probs))
编辑:正如Martijn Pieters所指出的,itertools.accumulate的文档包含以下函数,适用于Python 2:

def accumulate(iterable, func=operator.add):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    total = next(it)
    yield total
    for element in it:
        total = func(total, element)
        yield total

这应该用来代替上面解决方案中的partial_sums()。