0
0
NumPydata~20 mins

np.abs() for absolute values in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Absolute Value Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of np.abs() on mixed array
What is the output of this code?
import numpy as np
arr = np.array([-3, 0, 4, -7])
result = np.abs(arr)
print(result)
NumPy
import numpy as np
arr = np.array([-3, 0, 4, -7])
result = np.abs(arr)
print(result)
A[3 0 4 7]
B[-3 0 4 -7]
C[3 0 -4 7]
D[0 3 4 7]
Attempts:
2 left
💡 Hint
np.abs() returns the absolute value of each element in the array.
data_output
intermediate
2:00remaining
Absolute values of a 2D numpy array
Given this 2D array, what is the output of np.abs() applied to it?
import numpy as np
arr = np.array([[1, -2], [-3, 4]])
result = np.abs(arr)
print(result)
NumPy
import numpy as np
arr = np.array([[1, -2], [-3, 4]])
result = np.abs(arr)
print(result)
A
[[-1 2]
 [3 -4]]
B
[[1 -2]
 [-3 4]]
C
[[1 2]
 [3 4]]
D
[[1 2]
 [-3 4]]
Attempts:
2 left
💡 Hint
np.abs() works element-wise on arrays of any shape.
🧠 Conceptual
advanced
2:00remaining
Effect of np.abs() on complex numbers
What does np.abs() return when applied to a numpy array of complex numbers?
import numpy as np
arr = np.array([3+4j, 1-1j])
result = np.abs(arr)
print(result)
NumPy
import numpy as np
arr = np.array([3+4j, 1-1j])
result = np.abs(arr)
print(result)
A[5. 1.41421356]
B[3.+4.j 1.-1.j]
C[7.+0.j 2.+0.j]
D[-3.-4.j -1.+1.j]
Attempts:
2 left
💡 Hint
np.abs() returns the magnitude (distance from zero) for complex numbers.
🔧 Debug
advanced
2:00remaining
Identify the error in np.abs() usage
What error will this code raise?
import numpy as np
arr = np.array(['-3', '4', '-5'])
result = np.abs(arr)
print(result)
NumPy
import numpy as np
arr = np.array(['-3', '4', '-5'])
result = np.abs(arr)
print(result)
ASyntaxError: invalid syntax
BValueError: invalid literal for int() with base 10
CNo error, output: [3 4 5]
DTypeError: bad operand type for abs(): 'str'
Attempts:
2 left
💡 Hint
np.abs() expects numeric types, not strings.
🚀 Application
expert
3:00remaining
Using np.abs() to find max absolute difference
Given two numpy arrays, which option correctly finds the maximum absolute difference between their elements?
import numpy as np
a = np.array([1, -3, 5])
b = np.array([4, -1, -6])
max_diff = ???
print(max_diff)
NumPy
import numpy as np
a = np.array([1, -3, 5])
b = np.array([4, -1, -6])
max_diff = ???
print(max_diff)
Anp.abs(np.max(a) - np.max(b))
Bnp.max(np.abs(a - b))
Cnp.max(a) - np.min(b)
Dnp.abs(np.min(a) - np.min(b))
Attempts:
2 left
💡 Hint
Find the absolute difference element-wise, then get the max.