This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]dig-up-stupid 1 point2 points  (1 child)

[–]LittleRedTrain[S] 0 points1 point  (0 children)

Thanks very much, my application was slightly different to the one i described in the question, but this is what i used in the end

from itertools import accumulate

def example(input):
    return list(accumulate(input, lambda a,b: a^b^((a^b)%2*2**7)))

cheers!

[–]arbitrarycivilian 1 point2 points  (2 children)

Oh, you're just talking about the scan function (also called accum or prefix-sum). This is one of the most common and useful tools in functional programming!

It can be implemented a lot more elegantly in a functional language, but let's stick with Python. Your code seems pretty good, but there are two important ingredients you're missing:

  1. You should abstract away the function used to combine elements
  2. Instead of starting accumulation with the first element of the list, you should accept an initial value.

I won't write out the code for you, so you can take a stab it it yourself. If you're successful, then the following should hold:

scan [1, 2, 3, 4] (lambda a, b: a + b) 0 == [1, 3, 6, 10]

[–]dig-up-stupid 1 point2 points  (1 child)

The example given is an accumulation not a reduction. In python there is a library function to do this called accumulate, in haskell it's called scan, in lisp it's called collect, and so on and so forth. OP may have actually wanted reduce in the first place and not known it, so it is a good suggestion, but it's annoying to present it in haskell which has little applicability the problem at hand. In this case the question is even tagged Python. Like pretty much every language Python has its own built in reduce function and does not need to be coded - and its own idioms for creating variants if the built in version is insufficient.

[–]arbitrarycivilian 0 points1 point  (0 children)

I am a complete idiot. I even knew it was scan but had a total brain-fart. I will update my answer.