Home > Back-end >  Formatting and comparing arrays Numpy Python
Formatting and comparing arrays Numpy Python

Time:11-13

I am trying to check if the formatted vector a_and_b[::2] is equivalent to a, but it is giving me an error ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(). How would I be able to fix that and get the Expected Output?

import numpy as np 

a = np.array([5,32,1,4])
b = np.array([1,5,11,3])
a_and_b = np.array([5,1,32,5,1,11,4,3])
result = 'yes'  if a_and_b[::2] == a else 'no'

Expoected output:

yes

CodePudding user response:

You probably want to use this:

(a_and_b[::2] == a).all()

which will return True if all of the elements of each array are equal, since:

>>> a_and_b[::2] == a
array([ True,  True,  True,  True])

returns an array of True/False. all() will indicate whether all the elements of that array are True or not.

So try:

result = 'yes' if (a_and_b[::2] == a).all() else 'no'
  • Related