7

The code is a little complex, sorry. Please focus on the parallel_p function. Although sign is a tuple, Python complains:

if sign in hashtable and gives a TypeError. Why is sign a numpy.ndarray rather than a tuple? I created it as a tuple.

p_dist = dict()

def parallel_prog(hashtable):
    def wrapper(func):
        if parallel_programming:
            @wraps(func)
            def parallel_p(*args, **kwargs):
                sign = tuple(args) 
                print type(sign)
                if sign in hashtable:
                    r = hashtable[sign] # hit.
                    return r
                r = func(*args, **kwargs)
                hashtable[tuple(sign)] = r # register for future hits.
                return r
            return parallel_p
        else:
            return func
    return wrapper


@parallel_prog(p_dist)
def euclidean(a, b, signature=None):

    val = np.sqrt(np.add.reduce((a - b)**2))
    return val

IN TEST MODULE

class similartyTest(unittest.TestCase):

    def setUp(self):
        self.t = np.array([1,2,3,4])
        self.t1 = np.array([0, 0, 0, 0])
        self.t2 = np.array([4,3,2,1])
        self.h1 = [1,0,0,1,1]
        self.h2 = [1,1,1,1,1]

    def test_euclidean(self):
        self.failUnless(euclidean(self.t, self.t) == 0)
        self.failUnless(euclidean(self.t, self.t1) == sqrt(30))

OUTPUT:

<type 'tuple'>`

TypeError: unhashable type: 'numpy.ndarray`
4

2 回答 2

15

并非每个元组都是可散列的。包含不可散列项的元组不可散列:

>>> x = ([], [])
>>> hash(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

您的元组显然包含一个 NumPy 数组,它远非可散列的类型。

于 2011-11-09T22:17:31.690 回答
1

只有当元组拥有可散列的引用时,它们才是可散列的。

t1 = (7, 'A')
t2 = (7, 'A', {1, 2, 3})

t1 是可散列的,但 t2 不是。

下面的链接给出了更详细的解释: https ://www.quora.com/Are-tuples-hashable-in-Python/answer/Luciano-Ramalho?srid=T4aW

于 2017-03-30T16:32:22.310 回答