Logic Functions – SolutionsΒΆ

Solutions demonstrating NumPy’s logic functions for truth testing (np.all, np.any), content inspection (np.isfinite, np.isinf, np.isnan), type testing (np.iscomplex, np.isreal, np.isscalar), logical operations (np.logical_and, np.logical_or, np.logical_xor, np.logical_not), and comparison (np.allclose, np.array_equal, np.greater, np.less, np.isclose).

import numpy as np
np.__version__

Truth Value TestingΒΆ

Solutions using np.all() and np.any() to test whether all or any elements satisfy a condition.

Q1. Let x be an arbitrary array. Return True if none of the elements of x is zero. Remind that 0 evaluates to False in python.

x = np.array([1,2,3])
print np.all(x)

x = np.array([1,0,3])
print np.all(x)

Q2. Let x be an arbitrary array. Return True if any of the elements of x is non-zero.

x = np.array([1,0,0])
print np.any(x)

x = np.array([0,0,0])
print np.any(x)

Array ContentsΒΆ

Solutions using np.isfinite(), np.isinf(), and np.isnan() to detect special floating-point values.

Q3. Predict the result of the following code.

x = np.array([1, 0, np.nan, np.inf])
#print np.isfinite(x)

Q4. Predict the result of the following code.

x = np.array([1, 0, np.nan, np.inf])
#print np.isinf(x)

Q5. Predict the result of the following code.

x = np.array([1, 0, np.nan, np.inf])
#print np.isnan(x)

Array Type TestingΒΆ

Solutions using np.iscomplex(), np.isreal(), and np.isscalar() to inspect element and object types.

Q6. Predict the result of the following code.

x = np.array([1+1j, 1+0j, 4.5, 3, 2, 2j])
#print np.iscomplex(x)

Q7. Predict the result of the following code.

x = np.array([1+1j, 1+0j, 4.5, 3, 2, 2j])
#print np.isreal(x)

Q8. Predict the result of the following code.

#print np.isscalar(3)
#print np.isscalar([3])
#print np.isscalar(True)

Logical OperationsΒΆ

Solutions using np.logical_and(), np.logical_or(), np.logical_xor(), and np.logical_not() for element-wise boolean algebra.

Q9. Predict the result of the following code.

#print np.logical_and([True, False], [False, False])
#print np.logical_or([True, False, True], [True, False, False])
#print np.logical_xor([True, False, True], [True, False, False])
#print np.logical_not([True, False, 0, 1])

ComparisonΒΆ

Solutions using np.allclose(), np.array_equal(), np.greater(), np.less(), np.equal(), and np.isclose() for array comparison.

Q10. Predict the result of the following code.

#print np.allclose([3], [2.999999])
#print np.array_equal([3], [2.999999])

Q11. Write numpy comparison functions such that they return the results as you see.

x = np.array([4, 5])
y = np.array([2, 5])
print np.greater(x, y)
print np.greater_equal(x, y)
print np.less(x, y)
print np.less_equal(x, y)

Q12. Predict the result of the following code.

#print np.equal([1, 2], [1, 2.000001])
#print np.isclose([1, 2], [1, 2.000001])