Python 求部分和时屈服的

Python 求部分和时屈服的,python,python-2.7,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 f

我需要找到一组概率的子列表,这样子列表的负二元对数之和为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)))
这会管用,但可惜不行

我找到了解决方案:

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

在上面的解决方案中,应该用它来代替部分总和。

您正在运行
sum()
,它返回一个值。这对于
takewhile()
循环来说不是一个合适的参数,而是会导致一个错误。如果不是内置的,那么
sum()
从何而来?另外,您是否打算使用
partial_sum(probs)
而不是
partial_sum(probabilities)
?您的第一个值已经超过1
next(ps)
返回
12.091043076201494
。您的
takewhile()
示例给了我一个语法错误(
lambda
拼写错误),您在其中使用了
partial_sum
,但没有定义它。您能否更新您的问题,为我们提供一段可行的代码?
itertools.acumate()
的文档包括一个在Python 2上运行良好的Python版本。
def partial_sums(iterable):
    total = 0
    for i in iterable:
        total += -1*log(i,2)
        if total >= 1.0:
            yield i
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))
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