Understanding Python List

Possible Duplicate:
List Accounting for Total

I am trying to write a short expression about understanding the list for creating cdf: For example:

print f([0.2, 0.3,0.1,0.4])
[0.2,0.5,0.6,1.0] 

The standard procedure will look like this (I want to write a list comprehension for the f () function):

def f(probabilities) :

    sum = 0
    returnList = []
    for count in probabilities:
        sum +=count
        returnList = returnList + [sum]
    return returnList

Edit: I found the numpy.cumsum () function. I will check if it uses a list.

+5
source share
3 answers

, ( , ) , , scanl ( reduce ). ireduce ( " " ):

def ireduce(f, state, it):
    for x in it:
        state = f(state, x)
        yield state

:

import operator

def f(probabilities):
    return ireduce(operator.add, 0, probabilities)

print(list(f([0.2, 0.3,0.1,0.4])))
# [0.2, 0.5, 0.6, 1.0]
+8
[sum(probabilities[:i+1]) for i in range(len(probabilities))]

, O (n ^ 2). Python . , .

+8

, reduce(), , :

a = [0.2, 0.3, 0.1, 0.4]
reduce((lambda result, val: (result[0] + val, result[1] + [result[0] + val])), a, (0, []))[1]

Python . :

    a = [0.2, 0.3, 0.1, 0.4]   
    def accumulate(result, val):
        return (result[0] + val, result[1] + [result[0] + val])

    reduce(accumulate, a, (0, []))[1]
+1

All Articles