Check if numpy's array_like is an empty array - python

Suppose a is an array_like and we want to check if it is empty. Two possible ways to accomplish this are:
if not a:
pass
if numpy.array(a).size == 0:
pass
The first solution would also evaluate to True if a=None. However I would like to only check for an empty array_like.
The second solution seems good enough for that. I was just wondering if there is a numpy built-in function for that or a better solution then to check for the size?

If you want to check if size is zero, you might use numpy.size function to get more concise code
import numpy
a = []
b = [1,2]
c = [[1,2],[3,4]]
print(numpy.size(a) == 0) # True
print(numpy.size(b) == 0) # False
print(numpy.size(c) == 0) # False

Related

How to check whether tensor values in a different tensor pytorch?

I have 2 tensors of unequal size
a = torch.tensor([[1,2], [2,3],[3,4]])
b = torch.tensor([[4,5],[2,3]])
I want a boolean array of whether each value exists in the other tensor without iterating. something like
a in b
and the result should be
[False, True, False]
as only the value of a[1] is in b
I think it's impossible without using at least some type of iteration. The most succinct way I can manage is using list comprehension:
[True if i in b else False for i in a]
Checks for elements in b that are in a and gives [False, True, False]. Can also be reversed to get elements a in b [False, True].
this should work
result = []
for i in a:
try: # to avoid error for the case of empty tensors
result.append(max(i.numpy()[1] == b.T.numpy()[1,i.numpy()[0] == b.T.numpy()[0,:]]))
except:
result.append(False)
result
Neither of the solutions that use tensor in tensor work in all cases for the OP. If the tensors contain elements/tuples that match in at least one dimension, the aforementioned operation will return True for those elements, potentially leading to hours of debugging. For example:
torch.tensor([2,5]) in torch.tensor([2,10]) # returns True
torch.tensor([5,2]) in torch.tensor([5,10]) # returns True
A solution for the above could be forcing the check for equality in each dimension, and then applying a Tensor Boolean add. Note, the following 2 methods may not be very efficient because Tensors are rather slow for iterating and equality checking, so converting to numpy may be needed for large data:
[all(torch.any(i == b, dim=0)) for i in a] # OR
[any((i[0] == b[:, 0]) & (i[1] == b[:, 1])) for i in a]
That being said, #yuri's solution also seems to work for these edge cases, but it still seems to fail occasionally, and it is rather unreadable.
If you need to compare all subtensors across the first dimension of a, use in:
>>> [i in b for i in a]
[False, True, False]
I recently also encountered this issue though my goal is to select those row sub-tensors not "in" the other tensor. My solution is to first convert the tensors to pandas dataframe, then use .drop_duplicates(). More specifically, for OP's problem, one can do:
import pandas as pd
import torch
tensor1_df = pd.DataFrame(tensor1)
tensor1_df['val'] = False
tensor2_df = pd.DataFrame(tensor2)
tensor2_df['val'] = True
tensor1_notin_tensor2 = torch.from_numpy(pd.concat([tensor1_df, tensor2_df]).reset_index().drop(columns=['index']).drop_duplicates(keep='last').reset_index().loc[np.arange(tensor1_df.shape[0])].val.values)

Python, check whether array elements are all same or not

I have an array, say [4 4 4 4 4], here the length is 5. In real case it could be 300. How to check whether all the elements are same, say in this case all are 4. If all elements have same value, the function return true, otherwise false. The element could be only interger and value could be either one of them: 0,1,2,3,4.
I could use a loop in Python as follows. But I am looking for a concise way or simple way to do that, say one line.
x= [4,4,4,4]
temp = x[0]
for ele in x:
if(temp != ele):
false
true
You can put elements into set() and then check if length of the set is equal to 1:
if len(set(x)) == 1:
print('All elements are same')
else:
print('Not same')
it might be more efficient not to iterate over the full list (as does the set constructor) but to stop at the first element that does not equal x0. all does that for you:
x = [4,4,4,4]
x0 = x[0]
print(all(item == x0 for item in x))
# True
this is basically the same version you had; only the loop will be much more efficient this way.
also note that true and false are not valid python identifiers. in python it is True and False.

Proper Subset function in Python

I want a function that will say if a subset is proper. So if they are identical it will return True, if they aren't then False. I have a very simple design but it doesn't account for the set's properties, which is if there are duplicates in the set it will delete them. It will also be identifical if one set is IN the other set.
Here's my code:
def proper_subset(S,T):
if S == T:
return True
else:
return False
Here's some test cases on what it does and what it SHOULD do:
#What it does
S = {1,2}
T = {1,2,3}
proper_subset(S,T)
>>> False
#What it should do
S = {1,2}
T = {1,2,3}
proper_subset(S,T)
>>> True
Please help!
In python the set entity supports addition and subtraction. So you can just check the lengths of the subtraction operations.
def properSubset(S,T):
return len(S-T)==0 and len(T-S)>0
Also as the comments mention you can just use '<'
def properSubset(S,T):
return S<T

Python Identifying Suffix within set of strings

doing an exercise on CheckIO and I'm wondering as to why this won't work. Given a set of strings, I'm trying to return True if any of the strings are suffixes of any other string in the set. False otherwise. Using itertools I'm generating the necessary permutations in tuples first. Then for each tuple (each i), I wanted to see the hard way if the second tuple was in the end of the first tuple (option1). The otherway was using the .endwith function (option2), but neither will work for me. Why are these two options flawed?
import itertools
def checkio(words_set):
for i in itertools.permutations(words_set, 2):
#option1 ---- if i[1] in i[0][-len(i[1]):]:
#option2 ---- if i[0].endswith(i[1]):
return True
else:
return False
examples:
checkio({"hello", "lo", "he"}) == True
checkio({"hello", "la", "hellow", "cow"}) == False
I know this works as an answer. But just wondering why my original methods wouldn't take.
def checkio(words_set):
for w1 in words_set:
for w2 in words_set:
if w1.endswith(w2) and w1 != w2:
return True
return False
Your return False should be at the end of the for loop, otherwise the function will return True/False at every first comparison and will ignore all subsequent comparisons:
import itertools
def checkio(words_set):
for i in itertools.permutations(words_set, 2):
if i[0].endswith(i[1]):
return True
return False
Since it's an exercise, I won't give you the full answer, but are you sure that you really want to return False in the else clause?
Its because you return False right after the first check. and if it fails it will returns False you need to put it out of your for loop!
But as a more pythonic way you can use combinations and a generator expression within any function :
>>> from itertools import combinations
>>> s={"hello", "lo", "he"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s,2)))
True
>>> s2={"hello", "la", "hellow", "cow"}
>>> any(i.endswith(j) or j.endswith(i) for i,j in (combinations(s2,2)))
False

What is the difference between "is None" and "== None"

I recently came across this syntax, I am unaware of the difference.
I would appreciate it if someone could tell me the difference.
The answer is explained here.
To quote:
A class is free to implement
comparison any way it chooses, and it
can choose to make comparison against
None mean something (which actually
makes sense; if someone told you to
implement the None object from
scratch, how else would you get it to
compare True against itself?).
Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None as a general rule.
class Foo:
def __eq__(self,other):
return True
foo=Foo()
print(foo==None)
# True
print(foo is None)
# False
In this case, they are the same. None is a singleton object (there only ever exists one None).
is checks to see if the object is the same object, while == just checks if they are equivalent.
For example:
p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent
But since there is only one None, they will always be the same, and is will return True.
p = None
q = None
p is q # True because they are both pointing to the same "None"
It depends on what you are comparing to None. Some classes have custom comparison methods that treat == None differently from is None.
In particular the output of a == None does not even have to be boolean !! - a frequent cause of bugs.
For a specific example take a numpy array where the == comparison is implemented elementwise:
import numpy as np
a = np.zeros(3) # now a is array([0., 0., 0.])
a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
a is None #compares object to object, outputs False
If you use numpy,
if np.zeros(3)==None: pass
will give you error when numpy does elementwise comparison

Categories

Resources