Reputation: 53
I am trying to write a code to check if n is the maximum of the array A if it is return True if it isnt return False but I have two conditions if the value is a multidimentional or unidimentional I don't know how to write that:
if [A is unidimentional]:
maximum=A[0]
for i in range(A.shape[0]):
if max(A[i],maximum)==A[i]:
maximum=A[i]
if max(n,maximum)!=n:
return False
return True
else:
maximum=A[0][0]
for i in range(A.shape[0]):
for j in range(A.shape[1]):
if max(A[i][j],maximum)==A[i][j]:
maximum=A[i][j]
if max(n,maximum)!=n:
return False
return True
if someone knows how I can write that condition it would be very helpful Thanks
Upvotes: 4
Views: 2088
Reputation: 3107
If the matrix is multidimensional then max will return a list.
Otherwise it will return an int.
if type(max(A))== list:
# do some stuff for handling multidimensional
else:
# do some stuff for handling unidimensional
Or you could use numpy in which case
np.max(A)
returns an int regardless of A's dimensions.
A =[[1,2,3,4],[1,4,5,6]]
max(A)
Out[57]: [1, 4, 5, 6]
np.max(A)
Out[64]: 6
Upvotes: 2
Reputation: 10150
If you just want to check whether an array is multidimensional, just check the length of the shape
of the array
arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
print len(arr.shape)
If that value is greater than 1, then your array is multidimensional
But if all you want to do is check whether n
is equal to the largest value in the array, you dont need to manually implement that. np.amax
will tell you that:
largest_element = np.amax(arr)
if n == largest_element:
return True
else:
return False
Upvotes: 2
Reputation: 19806
Try the following:
import numpy as np
my_array = np.array([[1,2,3],[4,5,6]])
d = len(my_array.shape)
print(d) # Output: 2
Now, you can test against d
, if its value is 2, then your array is 2 dimensions.
Upvotes: 3