Reduce, fold or scan (Left/Right)?
When should I use reduceLeft, reduceRight, foldLeft, foldRight, scanLeft or scanRight? I want an intuition/overview of their differences – possibly with some simple examples. 3 Answers 3
When should I use reduceLeft, reduceRight, foldLeft, foldRight, scanLeft or scanRight? I want an intuition/overview of their differences – possibly with some simple examples. 3 Answers 3
Is there any way to map/reduce/filter/etc a Set in JavaScript or will I have to write my own? Here’s some sensible Set.prototype extensions Set.prototype.map = function map(f) { var newSet = new Set(); for (var v of this.values()) newSet.add(f(v)); return newSet; }; Set.prototype.reduce = function(f,initial) { var result = initial; for (var v of this) … Read more
I’m using Python 3.2. Tried this: xor = lambda x,y: (x+y)%2 l = reduce(xor, [1,2,3,4]) And got the following error: l = reduce(xor, [1,2,3,4]) NameError: name ‘reduce’ is not defined Tried printing reduce into interactive console – got this error: NameError: name ‘reduce’ is not defined Is reduce really removed in Python 3.2? If that’s … Read more
There is nice Array method reduce() to get one value from the Array. Example: [0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){ return previousValue + currentValue; }); What is the best way to achieve the same with objects? I’d like to do this: { a: {value:1}, b: {value:2}, c: {value:3} }.reduce(function(previous, current, index, array){ return previous.value + current.value; }); … Read more
Say I want to sum a.x for each element in arr. arr = [ { x: 1 }, { x: 2 }, { x: 4 } ]; arr.reduce(function(a, b){ return a.x + b.x; }); // => NaN I have cause to believe that a.x is undefined at some point. The following works fine arr = … Read more
filter, map, and reduce work perfectly in Python 2. Here is an example: >>> def f(x): return x % 2 != 0 and x % 3 != 0 >>> filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23] >>> def cube(x): return x*x*x >>> map(cube, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, … Read more
I have to find the average of a list in Python. This is my code so far from functools import reduce l = [15, 18, 2, 36, 12, 78, 5, 6, 9] print(reduce(lambda x, y: x + y, l)) I’ve got it so it adds together the values in the list, but I don’t know … Read more