I can't compute a hash value for a given vector!

Dear Mentors:

In Exercise 09 of the assignment for Week 4, I got stuck in creating a hash table.
I understand the algorithm where a 1 is assigned if the sign of the dot product
of a given vector with 10 hyperplanes is positive, otherwise a 0 is assigned.

The list for storing these hash values is of dimension (1, 10), isn’t it?
The code below is my problematic part.

< My code >
h = 1 if sign_of_dot_product >= 0 else 0

< My error >
ValueError: The truth value of an array with more than one element is ambiguous.
Use a.any() or a.all()

This error seems to derive from the inappropriate indexing for the list.
But I can’t find any solution due to the lack of my grammatical knowledge of Python.
Could you please give me some advice?


Sorry, I found a solution by myself!

I was able to extract a 10-dimensional vector from the list, sign_of_dot_product.
Then, I checkd if each element of the vector is positive or negative.
After that, I stored the binary value into a list again by using the append() method.


If possible, I want to know a more efficeint way to solve my error above.
In fact, I used an empty list and a for-loop to store the corresponding hash values,
so I didn’t have to use the squeeze() function to remove an unused dimension.

There seems to be a better solution based on the element-wise computation.
I would appreciate it if you could give me extra information.



You can simply assign an array comparison to h, as follows :slight_smile:

h = sign_of_dot_product >= 0

h will be an array of boolean values (True/False) that are considered as 1/0 in calculation


That’s it!

Thank you so much, zakaria_hmamed.
Your response is what I really want.

The code you posted is effective for numpy arrays, not for ordinary Python lists, right?
Your advice on “boolean comparison” is quite informative to me.

Thank you again! I really appreciate your quick response.


You are welcome Setsuro

Yes it does not work for lists the same way. However you can iterate in a list and make an element-wise comparison. For example if sign_of_dot_product was a list, we can use the following :
h = [element >=0 for element in sign_of_dot_product]

h will be a list of True/False


1 Like

Thank you again, zakaria_hmaned!

If I use an ordinary Python list instead of a numpy array,
I should extract each element in the list and then compare it with 0 in a for-loop, right?

Throughout the communication with you, I could deepen my knowledge of Python.
Thanks a lot!


Yes I think so

You are welcome !!

1 Like