[Numpy-svn] r2848 - in trunk/numpy/lib: . tests

numpy-svn at scipy.org numpy-svn at scipy.org
Wed Jul 19 12:19:04 EDT 2006


Author: oliphant
Date: 2006-07-19 11:19:00 -0500 (Wed, 19 Jul 2006)
New Revision: 2848

Modified:
   trunk/numpy/lib/function_base.py
   trunk/numpy/lib/tests/test_function_base.py
Log:
Apply patch for unique from #154

Modified: trunk/numpy/lib/function_base.py
===================================================================
--- trunk/numpy/lib/function_base.py	2006-07-19 15:55:43 UTC (rev 2847)
+++ trunk/numpy/lib/function_base.py	2006-07-19 16:19:00 UTC (rev 2848)
@@ -491,17 +491,28 @@
             else: last = last - 1
     return filt[first:last]
 
-def unique(inseq):
-    """Return unique items (in sorted order) from a 1-dimensional sequence.
+
+import sys
+if sys.hexversion < 0x2040000:
+   from sets import Set as set
+
+def unique(x):
+    """Return sorted unique items from an array or sequence.
+
+    Example:
+    >>> unique([5,2,4,0,4,4,2,2,1])
+    array([0,1,2,4,5])
     """
-    # Dictionary setting is quite fast.
-    set = {}
-    for item in inseq:
-        set[item] = None
-    val = asarray(set.keys())
-    val.sort()
-    return val
-
+    try:
+        tmp = x.flatten()
+        tmp.sort()
+        idx = concatenate(([True],tmp[1:]!=tmp[:-1]))
+        return tmp[idx]
+    except AttributeError:
+        items = list(set(x))
+        items.sort()
+        return asarray(items)
+        
 def extract(condition, arr):
     """Return the elements of ravel(arr) where ravel(condition) is True
     (in 1D).

Modified: trunk/numpy/lib/tests/test_function_base.py
===================================================================
--- trunk/numpy/lib/tests/test_function_base.py	2006-07-19 15:55:43 UTC (rev 2847)
+++ trunk/numpy/lib/tests/test_function_base.py	2006-07-19 16:19:00 UTC (rev 2848)
@@ -353,8 +353,16 @@
         (a,b)=histogram(linspace(0,10,100))
         assert(all(a==10))
 
+class test_unique(NumpyTestCase):
+    def check_simple(self):
+        x = array([4,3,2,1,1,2,3,4, 0])
+        assert(all(unique(x) == [0,1,2,3,4]))
+        assert(unique(array([1,1,1,1,1])) == array([1]))
+        x = ['widget', 'ham', 'foo', 'bar', 'foo', 'ham']
+        assert(all(unique(x) ==  ['bar', 'foo', 'ham', 'widget']))
+        x = array([5+6j, 1+1j, 1+10j, 10, 5+6j])
+        assert(all(unique(x) == [1+1j, 1+10j, 5+6j, 10]))
 
-
 def compare_results(res,desired):
     for i in range(len(desired)):
         assert_array_equal(res[i],desired[i])




More information about the Numpy-svn mailing list