Suma iloczynów liczb z listy [python]

0

Ma ktoś jakąś podpowiedź w jaki sposób znaleźć sumę iloczynów liczb z listy? Chodzi mi o taką sytuację: mam listę [5, 3, 7] i chcę ją zapisać w następujący sposób 5+(53)+(53*7). Chciałbym żeby to wszystko wykonywało się w jednej pętli. Jakieś pomysły?

1
5+(5*3)+(5*3*7)=
(5*3*7)+(5*3)+(5)=
(7*3*5)+(3*5)+(5)=
((7*3)+(3)+1)*5=
((7+1)*3+1)*5=
(((0+1)*7+1)*3+1)*5
2
from operator import mul
nums = [5, 3, 7]
print sum(reduce(mul, nums[:off+1]) for off in xrange(len(nums)))
# alternatywnie (inspirujac sie wzorem @_13th_Dragon)
print reduce(lambda total, x: (total + 1) * x, reversed(nums))
1

Prosta pętla:

# source: http://stackoverflow.com/a/14759302
def cum_fact(arr):
    cumulative_sum = 0
    latest_factorial = 1
    for a in arr:
        latest_factorial *= a
        cumulative_sum += latest_factorial
    return cumulative_sum
    
nums = [5, 3, 7]
print(cum_fact(nums))

http://ideone.com/T577Yi

0

Zgodnie z tym: http://4programmers.net/Forum/1232806 -

def cum_fact(arr):
    cumulative_sum = 0
    for a in arr[::-1]:
        cumulative_sum = (cumulative_sum + 1) * a
    return cumulative_sum
 
nums = [5, 3, 7]
print(cum_fact(nums))

1 użytkowników online, w tym zalogowanych: 0, gości: 1