Skip to content

Commit

Permalink
hash un-hashable point-types as tuples, fixes #12
Browse files Browse the repository at this point in the history
  • Loading branch information
stefankoegl committed Mar 30, 2014
1 parent 172aed4 commit be6e639
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
6 changes: 5 additions & 1 deletion kdtree.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,11 @@ def __eq__(self, other):
return self.data == other.data

def __hash__(self):
return hash(self.data)
try:
return hash(self.data)
except TypeError:
# try to hash un-hashable types as tuples
return hash(tuple(self.data))


def require_axis(f):
Expand Down
16 changes: 16 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import logging
import unittest
import doctest
import collections
from itertools import islice

import kdtree
Expand Down Expand Up @@ -234,6 +235,21 @@ def test_search_nn_dist(self):
self.assertTrue( (6,5) in nn)


class PointTypeTests(unittest.TestCase):
""" test using different types as points """

def test_point_types(self):
emptyTree = kdtree.create(dimensions=3)
point1 = (2, 3, 4)
point2 = [4, 5, 6]
Point = collections.namedtuple('Point', 'x y z')
point3 = Point(5, 3, 2)
tree = kdtree.create([point1, point2, point3])
res = tree.search_nn( (1, 2, 3) )

self.assertEqual(res, kdtree.KDNode( (2, 3, 4) ))


def random_tree(nodes=20, dimensions=3, minval=0, maxval=100):
points = list(islice(random_points(), 0, nodes))
tree = kdtree.create(points)
Expand Down

0 comments on commit be6e639

Please sign in to comment.