Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python reduce to check if all elements are equal

Tags:

python

reduce

Suppose a = [[1,2,3],[1,2,3]] reduce(lambda x,y: x==y, a) returns True

But if a = [[1,2,3],[1,2,3],[1,2,3]] reduce(lambda x,y: x==y, a) returns False

Why in the second case, the outcome is False?

please help

thanks

like image 474
Jack Avatar asked May 23 '12 00:05

Jack


4 Answers

You can still use reduce! Check out this magic:

bool(reduce(lambda x,y: (x==y)*x, a))

Since the return value of the lambda for x==y is True or False, that can be multiplied by the input and then used in the next comparison because True*[1,2,3] is [1,2,3]. It also works for strings, True*"MyString" is "MyString".

Try it. However, this method will not work for a list of zeros.

like image 87
billiam Avatar answered Oct 24 '22 01:10

billiam


Try this instead, it works for lists of any size:

all(e == a[0] for e in a)

Notice that your proposed solution using reduce doesn't work for more than two items, as the accumulated value after the first comparison is True, and you'd be comparing True against each of the elements from that point on, and obviously that's not going to work.

like image 22
Óscar López Avatar answered Oct 24 '22 01:10

Óscar López


You are not reducing the lists. The return value of your lambda is True or False, which is then used as input parameters to further calls to the same lambda function. So you end up comparing a boolean with a list. Therefore, the reducing function should return the same type as it input parameters.

You were probably looking for what other answers proposed instead: use all().

like image 5
C2H5OH Avatar answered Oct 24 '22 02:10

C2H5OH


Because first time reduce compare [1,2,3] == [1, 2, 3] and it's true next time it compare True and [1,2,3] and it's false.

help(reduce)

Help on built-in function reduce in module __builtin__:

reduce(...)
    reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).
like image 2
ddzialak Avatar answered Oct 24 '22 03:10

ddzialak