3
$\begingroup$

I have a problem with one code and hope that you can help me with that.

I have a list which looks like the following

List = {a, b, c, d, e}

the desired result is a new list with

{a, a*b, a*b*c, a*b*c*d, a*b*c*d*e}

Thanks in advance

$\endgroup$
5
  • $\begingroup$ Like Fold[Times, 1, list]? Also List is a built-in symbol, so don't use it as a variable. Stick to variables starting with lower-case letters. $\endgroup$ Commented Jan 31, 2020 at 16:11
  • $\begingroup$ @J.M. your command returns abcde. The OP asks that this is the final element of the new list created by multiplication of the elements of the original ones. $\endgroup$
    – user49048
    Commented Jan 31, 2020 at 16:16
  • 5
    $\begingroup$ Oops, that should be FoldList[] and not Fold[]; thanks @Darth! $\endgroup$ Commented Jan 31, 2020 at 16:17
  • $\begingroup$ @J.M.isinlimbo that's the trick, yes. I tried to do it using Nest, NestList and failed spectacularly :-) $\endgroup$
    – user49048
    Commented Jan 31, 2020 at 16:18
  • 1
    $\begingroup$ FoldList[Times, {a, b, c, d,e}] $\endgroup$ Commented Feb 1, 2020 at 5:25

5 Answers 5

6
$\begingroup$

Accumulate takes the sum of the terms: this can be changed to the product of by changing the Plus to Times:

 list = {a, b, c, d, e};
 Accumulate@list /. Plus -> Times
 {a, a b, a b c, a b c d, a b c d e}
$\endgroup$
1
  • 3
    $\begingroup$ Alternatively Block[{Plus = Times}, Accumulate@list] if you don't want to use replacements. $\endgroup$ Commented Feb 1, 2020 at 5:58
4
$\begingroup$

Another way:

list = {a, b, c, d, e};
E^Accumulate[Log[list]]

Since Accumulate equals Rest[FoldList[Plus,0,list]] , So Foldlist also works.

$\endgroup$
4
$\begingroup$

Another:

ReplaceList[{a, b, c, d,e}, { x__,___} :> Times@x ] 

{a, a b, a b c, a b c d, a b c d e}

Comparing:

ReplaceList[{a, b, c, d,e}, { x__,___} :> Times@x ] == FoldList[Times] @ {a, b, c, d,e}

True

$\endgroup$
3
$\begingroup$

Here's an operator version of @JM's suggestion in the comments:

list = {a, b, c, d, e};

FoldList[Times] @ list

{a, a b, a b c, a b c d, a b c d e}

$\endgroup$
3
$\begingroup$
list = {a, b, c, d, e};

Using TimesBy

Module[{a = 1}, a *= # & /@ list]

{a, a b, a b c, a b c d, a b c d e}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.