“Reduce” function for Series

With itertools.chain() on the values This could be faster: from itertools import chain categories = list(chain.from_iterable(categories.values)) Performance from functools import reduce from itertools import chain categories = pd.Series([[‘a’, ‘b’], [‘c’, ‘d’, ‘e’]] * 1000) %timeit list(chain.from_iterable(categories.values)) 1000 loops, best of 3: 231 µs per loop %timeit list(chain(*categories.values.flat)) 1000 loops, best of 3: 237 µs per … Read more

python : can reduce be translated into list comprehensions like map, lambda and filter?

It is no secret that reduce is not among the favored functions of the Pythonistas. Generically, reduce is a left fold on a list It is conceptually easy to write a fold in Python that will fold left or right on a iterable: def fold(func, iterable, initial=None, reverse=False): x=initial if reverse: iterable=reversed(iterable) for e in … Read more

Equivalent of Scala’s foldLeft in Java 8

There is no equivalent of foldLeft in Java 8’s Stream API. As others noted, reduce(identity, accumulator, combiner) comes close, but it’s not equivalent with foldLeft because it requires the resulting type B to combine with itself and be associative (in other terms, be monoid-like), a property that not every type has. There is also an … Read more

array.push is not a function – when working with reduce [duplicate]

The return value of Array#push is the new length of the array after the push. This means that in the second iteration acc is a number, which doesn’t have the push method. The fix is simple – separate the push and return statements: const secondArray = [1, 2, 3].reduce((acc, item) => { acc.push(1); return acc; … Read more

Java Stream: divide into two lists by boolean predicate

Collectors.partitioningBy: Map<Boolean, List<Employee>> partitioned = listOfEmployees.stream().collect( Collectors.partitioningBy(Employee::isActive)); The resulting map contains two lists, corresponding to whether or not the predicate was matched: List<Employee> activeEmployees = partitioned.get(true); List<Employee> formerEmployees = partitioned.get(false); There are a couple of reasons to use partitioningBy over groupingBy (as suggested by Juan Carlos Mendoza): Firstly, the parameter of groupingBy is a Function<Employee, … Read more

Count the number of true members in an array of boolean values

Seems like your problem is solved already, but there are plenty of easier methods to do it. Excellent one: .filter(Boolean); // will keep every truthy value in an array const arr = [true, false, true, false, true]; const count = arr.filter(Boolean).length; console.log(count); Good one: const arr = [true, false, true, false, true]; const count = … Read more

tech