Stack Overflow Asked by Sebaku on November 22, 2020
Let’s say I have 3 lists:
a = [0,0,0,1,1]
b = [1,0,0,0,0]
c = [1,1,1,0,0]
I want to return False whenever there are 1’s at the same position, so for ‘b & c’ it would return False, because they both have a one at index 0, ‘a & b’ and ‘a & c’ should return True in this case.
The way I would do it is:
for i in range(0, len(a)):
if a[i] == 1 and b[i] == 1:
return False
return True
Though I feel this is very inefficient. Is there an easier and more efficient way to do this? I was thinking of using binary AND, but not sure how to implement that.
Are you looking for one liner. Here it is:
any([False if a[i] == 1 and b[i] == 1 else True for i in range(0, len(a))])
Sorry did not test it. Here is modified version with test:
>>> a = [0,0,0,1,1]
>>> b = [1,0,0,0,0]
>>> c = [1,1,1,0,0]
>>> def f(a,b):
... return all([False if a[i] == 1 and b[i] == 1 else True for i in range(0, len(a))])
...
>>> print(f(a,b), f(b,c), f(a,c))
True False True
Answered by Aaj Kaal on November 22, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP