In Python3, I am looking for a way to compute in one line a lambda
function called on elements two by two. Let’s say I want to compute the LCM of a list of integers, this can be done in one line in Python2:
print reduce(lambda a,b: a * b // gcd(a, b), mylist)
Is it possible to do the same in one line Python3 (implied, without functools.reduce
)?
In Python3 I know that filter
, map
and reduce
are gone. I don’t feel I need filter
and map
anymore because they can be written in Python3 in a shorter and more clear fashion but I thought I could find a nice replacement for reduce
as well, except I haven’t found any. I have seen many articles that suggest to use functools.reduce
or to “write out the accumulation loop explicitly” but I’d like to do it without importing functools and in one line.
If it makes it any easier, I should mention I use functions that are both associative and commutative. For instance with a function f
on the list [1,2,3,4]
, the result will be good if it either computes:
f(1,f(2,f(3,4)))
f(f(1,2),f(3,4))
f(f(3,f(1,4)),2)
- or any other order