[pypy-svn] r25996 - in pypy/dist/pypy/objspace/constraint: . test

auc at codespeak.net auc at codespeak.net
Wed Apr 19 19:06:04 CEST 2006


Author: auc
Date: Wed Apr 19 19:05:59 2006
New Revision: 25996

Added:
   pypy/dist/pypy/objspace/constraint/btree.py
   pypy/dist/pypy/objspace/constraint/test/test_btree.py
   pypy/dist/pypy/objspace/constraint/util.py
Modified:
   pypy/dist/pypy/objspace/constraint/computationspace.py
   pypy/dist/pypy/objspace/constraint/constraint.py
   pypy/dist/pypy/objspace/constraint/distributor.py
   pypy/dist/pypy/objspace/constraint/domain.py
   pypy/dist/pypy/objspace/constraint/test/test_computationspace.py
   pypy/dist/pypy/objspace/constraint/test/test_constraint.py
   pypy/dist/pypy/objspace/constraint/test/test_distributor.py
   pypy/dist/pypy/objspace/constraint/test/test_solver.py
Log:
bunch of changes to help translatability


Added: pypy/dist/pypy/objspace/constraint/btree.py
==============================================================================
--- (empty file)
+++ pypy/dist/pypy/objspace/constraint/btree.py	Wed Apr 19 19:05:59 2006
@@ -0,0 +1,72 @@
+
+class Found(Exception): pass
+
+class BTree(object):
+    """binary tree"""
+
+    def __init__(self):
+        self.leaf = True
+
+    def _populate(self, key, val):
+        self.leaf = False
+        self.key = key
+        self.val = val
+        self.left = BTree()
+        self.right = BTree()
+
+    def add(self, key, val):
+        if self.leaf:
+            self._populate(key, val)
+        else:
+            if key > self.key:
+                self.right.add(key, val)
+            else:
+                self.left.add(key, val)
+
+    def _in(self, key):
+        if self.leaf:
+            return False
+        if self.key == key: raise Found
+        self.left._in(key)
+        self.right._in(key)
+
+    def __contains__(self, key):
+        if self.leaf: return False
+        if self.key == key: return True
+        try:
+            self._in(key)
+            self._in(key)
+            return False
+        except Found:
+            return True
+
+    def _infixly(self, output, ret=0):
+        """depending on the value of ret:
+           0 : keys
+           1 : values
+           2 : both (items)
+        """
+        if self.leaf: return
+        self.left._infixly(output, ret)
+        if ret == 0:
+            output.append(self.key)
+        elif ret == 1:
+            output.append(self.val)
+        else:
+            output.append((self.key, self.val))
+        self.right._infixly(output, ret)
+
+    def keys(self):
+        out = []
+        self._infixly(out, ret=0)
+        return out
+
+    def values(self):
+        out = []
+        self._infixly(out, ret=1)
+        return out
+
+    def items(self):
+        out = []
+        self._infixly(out, ret=2)
+        return out

Modified: pypy/dist/pypy/objspace/constraint/computationspace.py
==============================================================================
--- pypy/dist/pypy/objspace/constraint/computationspace.py	(original)
+++ pypy/dist/pypy/objspace/constraint/computationspace.py	Wed Apr 19 19:05:59 2006
@@ -6,7 +6,7 @@
 from pypy.objspace.std.stringobject import W_StringObject
 
 from pypy.objspace.constraint.domain import W_AbstractDomain
-
+from pypy.objspace.constraint.util import sort, reverse
 
 all_mms = {}
 
@@ -15,13 +15,13 @@
 class W_Variable(Wrappable):
     def __init__(self, obj_space, w_name):
         self._space = obj_space
-        self.w_name = w_name
+        self._name = w_name
 
     def name_w(self):
-        return self._space.str_w(self.w_name)
+        return self._space.str_w(self._name)
     
     def w_name(self):
-        return self.w_name
+        return self._name
 
 W_Variable.typedef = typedef.TypeDef(
     "W_Variable",
@@ -33,33 +33,18 @@
     def __init__(self, object_space):
         self._space = object_space
 
-    def w_affected_variables(self):
-        pass
-
-    def w_is_variable_relevant(self, w_var):
-        pass
-
-    def w_estimate_cost(self, w_cs):
-        pass
-
-    def w_revise(self, w_cs):
-        pass
-    
 W_Constraint.typedef = typedef.TypeDef(
-    "W_Constraint",
-    affected_variables = interp2app(W_Constraint.w_affected_variables),
-    is_variable_relevant = interp2app(W_Constraint.w_is_variable_relevant),
-    estimate_cost = interp2app(W_Constraint.w_estimate_cost),
-    revise = interp2app(W_Constraint.w_revise))
+    "W_Constraint")
 
 
 #-- Distributors (standards) ------------
 
 class W_Distributor(Wrappable):
 
-    def __init__(self, object_space, fanout_w):
+    def __init__(self, object_space, fanout):
+        assert isinstance(fanout, int)
         self._space = object_space
-        self.fanout = fanout_w
+        self._fanout = fanout
 
 W_Distributor.typedef = typedef.TypeDef("W_Distributor")
 
@@ -99,7 +84,7 @@
         except: # FIXME: indexError ?
             self.status = self._space.newint(1)
             return self.status
-        self.status = self._space.newint(self.distributor.fanout)
+        self.status = self.distributor.w_fanout()
         return self.status
 
     def w_clone(self):
@@ -148,7 +133,9 @@
         return self._space.newlist(res)
 
     def w_dom(self, w_variable):
-        assert isinstance(w_variable, W_Variable)
+        if not isinstance(w_variable, W_Variable):
+            raise OperationError(self._space.w_RuntimeError,
+                                 self._space.wrap("dom() takes a variable"))
         return self.var_dom[w_variable]
 
     def w_tell(self, w_constraint):
@@ -172,22 +159,24 @@
         return self._space.newtuple(res)
 
     def w_test_solution(self, w_sol):
-        varset = {}
-        for var, val in zip(self.sol_set.wrappeditems,
-                            w_sol.wrappeditems):
-            varset[var.w_name] = val
-        for _const in self.constraints:
-            if not _const.test_solution(varset):
-                print "Solution", sol, "doesn't satisfy", _const
-                return self._space.newbool(False)
-        return self._space.newbool(True)
+        pass
+##         varset = {}
+##         for var, val in zip(self.sol_set.wrappeditems,
+##                             w_sol.wrappeditems):
+##             varset[var.w_name()] = val
+##         for _const in self.constraints:
+##             if not _const.test_solution(varset):
+##                 #print "Solution", sol, "doesn't satisfy", _const
+##                 return self._space.newbool(False)
+##         return self._space.newbool(True)
 
 
     def w_print_state(self):
-        print "VARS  :", self.name_var.keys()
-        print "CONST :", self.var_const.values()
-        print "DOMS  :", self.var_dom.values()
-        print "CHK   :", self.to_check
+        pass
+##         print "VARS  :", self.name_var.keys()
+##         print "CONST :", self.var_const.values()
+##         print "DOMS  :", self.var_dom.values()
+##         print "CHK   :", self.to_check
 
     #-- everything else ---------------
 
@@ -202,8 +191,8 @@
                    for const in self.to_check]
         self.to_check = {}
         assert const_q != []
-        const_q.sort()
-        const_q.reverse() # for pop() friendlyness
+        sort(const_q)
+        reverse(const_q) # for pop() friendlyness
         affected_constraints = {}
         while True:
             if not const_q:

Modified: pypy/dist/pypy/objspace/constraint/constraint.py
==============================================================================
--- pypy/dist/pypy/objspace/constraint/constraint.py	(original)
+++ pypy/dist/pypy/objspace/constraint/constraint.py	Wed Apr 19 19:05:59 2006
@@ -2,14 +2,23 @@
 from pypy.interpreter.baseobjspace import Wrappable
 from pypy.interpreter import baseobjspace, typedef, gateway
 from pypy.interpreter.gateway import interp2app
+from pypy.interpreter.function import Function
 
 from pypy.objspace.std.listobject import W_ListObject
+from pypy.objspace.std.stringobject import W_StringObject
 
 from pypy.objspace.constraint.computationspace import W_ComputationSpace
-from pypy.objspace.constraint.computationspace import W_Constraint
+from pypy.objspace.constraint.computationspace import W_Constraint, W_Variable
+
+from pypy.objspace.std.model import StdObjSpaceMultiMethod
+
+from pypy.objspace.constraint.btree import BTree
 
 import operator
 
+all_mms = {}
+
+
 #-- Exceptions ---------------------------------------
 
 class ConsistencyFailure(Exception):
@@ -23,7 +32,6 @@
 
 #-- Constraints ------------------------------------------
 
-
 class W_AbstractConstraint(W_Constraint):
     
     def __init__(self, object_space, w_variables):
@@ -45,7 +53,8 @@
         return self._variables
 
     def w_knows_var(self, w_variable):
-        return self._space.newbool(variable in self._variables)
+        assert isinstance(w_variable, W_Variable)
+        return self._space.newbool(w_variable in self._variables)
 
     def w_estimate_cost(self, w_cs):
         """Return an estimate of the cost of the narrowing of the constraint"""
@@ -58,15 +67,20 @@
 
     def estimate_cost_w(self, w_cs):
         assert isinstance(w_cs, W_ComputationSpace)
-        return reduce(operator.mul,
-                      [w_cs.w_dom(var).size()
-                       for var in self._variables])
-
-    def __eq__(self, other): #FIXME and parent
-        if not isinstance(other, self.__class__): return False
-        return self._variables == other._variables
+        v = 1
+        for var in self._variables:
+            v = v * w_cs.w_dom(var).size()
+        return v
+
+    
+
+##     def __eq__(self, other): #FIXME and parent
+##         if not isinstance(other, self.__class__): return False
+##         return self._variables == other._variables
     
-W_AbstractConstraint.typedef = typedef.TypeDef("W_AbstractConstraint",
+W_AbstractConstraint.typedef = typedef.TypeDef(
+    "W_AbstractConstraint",
+    W_Constraint.typedef,                                           
     affected_variables = interp2app(W_AbstractConstraint.w_affected_variables),
     knows_var = interp2app(W_AbstractConstraint.w_knows_var),
     estimate_cost = interp2app(W_AbstractConstraint.w_estimate_cost),
@@ -95,17 +109,25 @@
     def revise(self, w_cs):
         _spc = self._space
         assert isinstance(w_cs, W_ComputationSpace)
-        variables = [(_spc.int_w(w_cs.w_dom(variable).w_size()),
-                      variable, w_cs.w_dom(variable))
-                     for variable in self._variables]
+
+        ord_vars = BTree()
+        for variable in self._variables:
+            ord_vars.add(_spc.int_w(w_cs.w_dom(variable).w_size()),
+                         (variable, w_cs.w_dom(variable)))
+
+        variables = ord_vars.values()
+        
+##         variables = [(_spc.int_w(w_cs.w_dom(variable).w_size()),
+##                       variable, w_cs.w_dom(variable))
+##                      for variable in self._variables]
+##         variables.sort()
         
-        variables.sort()
         # if a domain has a size of 1,
         # then the value must be removed from the other domains
-        for size, var, dom in variables:
+        for var, dom in variables:
             if _spc.eq_w(dom.w_size(), _spc.newint(1)):
                 #print "AllDistinct removes values"
-                for _siz, _var, _dom in variables:
+                for _var, _dom in variables:
                     if not _spc.eq_w(_var, var):
                         try:
                             _dom.w_remove_value(dom.w_get_values().wrappeditems[0])
@@ -116,7 +138,7 @@
 
         # if there are less values than variables, the constraint fails
         values = {}
-        for size, var, dom in variables:
+        for var, dom in variables:
             for val in dom.w_get_values().wrappeditems:
                 values[val] = 0
 
@@ -126,8 +148,8 @@
                                  _spc.wrap("ConsistencyFailure"))
 
         # the constraint is entailed if all domains have a size of 1
-        for variable in variables:
-            if not _spc.eq_w(variable[2].w_size(),
+        for _var, dom in variables:
+            if not _spc.eq_w(dom.w_size(),
                              _spc.newint(1)):       
                 return False
 
@@ -138,23 +160,33 @@
 
 W_AllDistinct.typedef = typedef.TypeDef(
     "W_AllDistinct", W_AbstractConstraint.typedef,
-    estimate_cost = interp2app(W_AllDistinct.w_estimate_cost),
-    revise = interp2app(W_AllDistinct.w_revise))
+    estimate_cost = interp2app(W_AllDistinct.w_estimate_cost))
+#    revise = interp2app(W_AllDistinct.w_revise))
 
 # function bolted into the space to serve as constructor
 def make_alldistinct(object_space, w_variables):
+    assert len(w_variables.wrappeditems) > 0
     return object_space.wrap(W_AllDistinct(object_space, w_variables))
 app_make_alldistinct = gateway.interp2app(make_alldistinct)
 
 
-def make_filter(object_space, w_variables, w_formula):
+def make_filter__List_String(object_space, w_variables, w_formula):
     """NOT RPYTHON"""
-    var_ids = ','.join([object_space.str_w(var.w_name)
+    assert isinstance(w_variables, W_ListObject)
+    assert isinstance(w_formula, W_StringObject)
+    var_ids = ','.join([var.name_w()
                         for var in w_variables.wrappeditems])
     func_head = 'lambda ' + var_ids + ':'
-    func_obj = eval(func_head + object_space.str_w(w_formula), {}, {})
+    expr = func_head + object_space.str_w(w_formula)
+    func_obj = object_space.eval(expr, object_space.newdict({}),
+                                 object_space.newdict({}))
+    assert isinstance(func_obj, Function)
     return func_obj
-app_make_filter = gateway.interp2app(make_filter)
+
+make_filter_mm = StdObjSpaceMultiMethod('make_filter', 2)
+make_filter_mm.register(make_filter__List_String, W_ListObject, W_StringObject)
+all_mms['make_filter'] = make_filter_mm
+
 
 class W_Expression(W_AbstractConstraint):
     """A constraint represented as a python expression."""
@@ -164,21 +196,21 @@
         formula is a python expression that will be evaluated as a boolean"""
         W_AbstractConstraint.__init__(self, object_space, w_variables)
         self.formula = self._space.str_w(w_formula)
-        self.filter_func = make_filter(self._space, w_variables, w_formula)
+        self.filter_func = self._space.make_filter(w_variables, w_formula)
 
     def test_solution(self, sol_dict):
         """test a solution against this constraint 
         accept a mapping of variable names to value"""
         args = []
         for var in self._variables:
-            args.append(sol_dict[var.w_name])
+            args.append(sol_dict[var.w_name()])
         return self.filter_func(*args)
 
     def _init_result_cache(self):
         """key = (variable,value), value = [has_success,has_failure]"""
         result_cache = self._space.newdict({})
         for var in self._variables:
-            result_cache.content[var.w_name] = self._space.newdict({})
+            result_cache.content[var.w_name()] = self._space.newdict({})
         return result_cache
 
     def _assign_values(self, w_cs):
@@ -190,7 +222,7 @@
             variables.append((self._space.int_w(domain.w_size()),
                               [variable, values, self._space.newint(0),
                                self._space.len(values)]))
-            kwargs.content[variable.w_name] = values.wrappeditems[0]
+            kwargs.content[variable.w_name()] = values.wrappeditems[0]
         # sort variables to instanciate those with fewer possible values first
         variables.sort()
 
@@ -201,11 +233,11 @@
             for size, curr in variables:
                 if self._space.int_w(curr[2]) + 1 < self._space.int_w(curr[-1]):
                     curr[2] = self._space.add(curr[2], self._space.newint(1))
-                    kwargs.content[curr[0].w_name] = curr[1].wrappeditems[self._space.int_w(curr[2])]
+                    kwargs.content[curr[0].w_name()] = curr[1].wrappeditems[self._space.int_w(curr[2])]
                     break
                 else:
                     curr[2] = self._space.newint(0)
-                    kwargs.content[curr[0].w_name] = curr[1].wrappeditems[0]
+                    kwargs.content[curr[0].w_name()] = curr[1].wrappeditems[0]
             else:
                 # it's over
                 go_on = 0
@@ -250,8 +282,8 @@
         return '<%s>' % self.formula
 
 W_Expression.typedef = typedef.TypeDef("W_Expression",
-    W_AbstractConstraint.typedef,
-    revise = interp2app(W_Expression.w_revise))
+    W_AbstractConstraint.typedef)
+#    revise = interp2app(W_Expression.w_revise))
 
 
 # completely unported
@@ -305,9 +337,6 @@
         except ConsistencyFailure:
             raise ConsistencyFailure('Inconsistency while applying %s' % \
                                      repr(self))
-        except Exception:
-            print self, kwargs
-            raise 
         return maybe_entailed
 
 
@@ -315,6 +344,7 @@
     """create a new constraint of type Expression or BinaryExpression
     The chosen class depends on the number of variables in the constraint"""
     # encode unicode
+    assert len(w_variables.wrappeditems) > 0
     return W_Expression(o_space, w_variables, w_formula)
     if o_space.eq_w(o_space.len(w_variables), o_space.newint(2)):
         return W_BinaryExpression(o_space, w_variables, w_formula)

Modified: pypy/dist/pypy/objspace/constraint/distributor.py
==============================================================================
--- pypy/dist/pypy/objspace/constraint/distributor.py	(original)
+++ pypy/dist/pypy/objspace/constraint/distributor.py	Wed Apr 19 19:05:59 2006
@@ -21,12 +21,11 @@
 class W_AbstractDistributor(W_Distributor):
     """_distribute is left unimplemented."""
 
-    def w_fanout(self):
-        return self._space.newint(self.fanout)
+    def __init__(self, objspace, fanout):
+        W_Distributor.__init__(objspace, fanout)
 
-    def fanout(self):
-        """return number of possible splits"""
-        return self.fanout
+    def w_fanout(self):
+        return self._space.newint(self._fanout)
 
     def _find_smallest_domain(self, w_cs):
         """returns the variable having the smallest domain.
@@ -34,6 +33,7 @@
         """
         vars_ = [var for var, dom in w_cs.var_dom.items()
                  if dom.size() > 1]
+        assert len(vars_) > 0
         best = vars_[0]
         for var in vars_:
             if w_cs.var_dom[var].size() < w_cs.var_dom[best].size():
@@ -54,7 +54,7 @@
     def find_distribution_variable(self, w_cs):
         return self._find_smallest_domain(w_cs)
     
-    def _do_distribute(self, domain, choice):
+    def _do_distribute(self, w_cs, domain, choice):
         """remove values from domain depending on choice"""
         raise NotImplementedError
 
@@ -69,14 +69,15 @@
     The first new domain has a size of one,
     and the second has all the other values"""
 
-    def __init__(self, object_space, fanout_w):
+    def __init__(self, object_space, fanout):
         # default fanout is 2, see make_naive_distributor
-        W_Distributor.__init__(self, object_space, fanout_w)
+        W_Distributor.__init__(self, object_space, fanout)
         
     def _do_distribute(self, w_cs, domain, choice):
         values = domain.get_values()
+        #assert len(values) > 0
         if choice == 0:
-            domain.w_remove_values(values[1:])
+            domain.remove_values(values[1:])
         else:
             domain.w_remove_value(values[0])
 
@@ -85,6 +86,9 @@
     W_AbstractDistributor.typedef)
 
 def make_naive_distributor(object_space, fanout=2):
+    if not isinstance(fanout, int):
+        raise OperationError(object_space.w_RuntimeError,
+                             object_space.wrap("fanout must be a positive integer"))
     return object_space.wrap(W_NaiveDistributor(object_space, fanout))
 app_make_naive_distributor = interp2app(make_naive_distributor,
                                         unwrap_spec = [baseobjspace.ObjSpace, int])
@@ -96,16 +100,16 @@
     If nb_subspaces is 0, then the smallest domain is split in
     domains of size 1"""
     
-    def __init__(self, object_space, fanout_w):
+    def __init__(self, object_space, fanout):
         # default fanout is 3, see make_split_distributor
-        W_Distributor.__init__(self, object_space, fanout_w)
+        W_Distributor.__init__(self, object_space, fanout)
 
     def _subdomains(self, w_cs):
         """returns the min number of partitions
            for a domain to be distributed"""
         to_split = self._find_smallest_domain(w_cs)
-        if self.fanout:
-            return min(self.fanout,
+        if self._fanout > 0:
+            return min(self._fanout,
                        w_cs.w_dom(to_split).size()) 
         else:
             return w_cs.w_dom(to_split).size() 
@@ -119,6 +123,9 @@
         domain.remove_values(values[end:])
 
 def make_split_distributor(object_space, fanout=3):
+    if not isinstance(fanout, int):
+        raise OperationError(object_space.w_RuntimeError,
+                             object_space.wrap("fanout must be a positive integer"))
     return object_space.wrap(W_SplitDistributor(object_space, fanout))
 app_make_split_distributor = interp2app(make_split_distributor,
                                         unwrap_spec = [baseobjspace.ObjSpace, int])
@@ -133,4 +140,3 @@
 def make_dichotomy_distributor(object_space):
     return make_split_distributor(object_space, 2)
 app_make_dichotomy_distributor = interp2app(make_dichotomy_distributor)
-

Modified: pypy/dist/pypy/objspace/constraint/domain.py
==============================================================================
--- pypy/dist/pypy/objspace/constraint/domain.py	(original)
+++ pypy/dist/pypy/objspace/constraint/domain.py	Wed Apr 19 19:05:59 2006
@@ -8,7 +8,6 @@
 
 from pypy.objspace.std.model import StdObjSpaceMultiMethod
 
-
 all_mms = {}
 
 class ConsistencyFailure(Exception):
@@ -33,12 +32,6 @@
     def has_changed(self):
         return self.__changed
 
-    def w_size(self):
-        return self._space.newint(self.size())
-
-    def size(self):
-        pass
-    
     def _value_removed(self):
         """The implementation of remove_value should call this method"""
         self.__changed = True
@@ -78,14 +71,23 @@
 
     def w_remove_values(self, w_values):
         """Remove values of domain and check for consistency"""
+        assert isinstance(w_values, W_ListObject)
         self.remove_values(w_values.wrappeditems)
 
     def remove_values(self, values):
-        if len(values) > 0:
-            for w_val in values:
-                del self._values[w_val]
-            self._value_removed()
-    
+        assert isinstance(values, list)
+        try:
+            if len(values) > 0:
+                for w_val in values:
+                    del self._values[w_val]
+                self._value_removed()
+        except:
+            raise OperationError(self._space.w_RuntimeError,
+                                 self._space.wrap("attempt to remove unkown value from domain"))
+
+    def w_size(self):
+        return self._space.newint(self.size())
+
     def size(self):
         """computes the size of a finite domain"""
         return len(self._values)

Added: pypy/dist/pypy/objspace/constraint/test/test_btree.py
==============================================================================
--- (empty file)
+++ pypy/dist/pypy/objspace/constraint/test/test_btree.py	Wed Apr 19 19:05:59 2006
@@ -0,0 +1,18 @@
+class AppTest_BTree(object):
+
+
+    def test_everything_at_once(self):
+        from pypy.objspace.constraint.btree import BTree
+        b = BTree()
+        l = [(-1, 'egg'), (-7, 'spam'), (3, 'bacon'),
+             (99, 'ham'), (77, 'cheese'), (7, 'tomato'),
+             (5, 'chicken'), (9, 'noodles')]
+        for k, v in l: b.add(k, v)
+        assert 77 in b
+        assert 66 not in b
+        assert b.values() == ['spam', 'egg', 'bacon', 'chicken',
+                               'tomato', 'noodles', 'cheese', 'ham']
+        assert b.keys() == [-7, -1, 3, 5, 7, 9, 77, 99]
+        assert b.items() == [(-7, 'spam'), (-1, 'egg'), (3, 'bacon'),
+                             (5, 'chicken'), (7, 'tomato'), (9, 'noodles'),
+                             (77, 'cheese'), (99, 'ham')]

Modified: pypy/dist/pypy/objspace/constraint/test/test_computationspace.py
==============================================================================
--- pypy/dist/pypy/objspace/constraint/test/test_computationspace.py	(original)
+++ pypy/dist/pypy/objspace/constraint/test/test_computationspace.py	Wed Apr 19 19:05:59 2006
@@ -128,7 +128,6 @@
             csp.tell(AllDistinct([x, y, z]))
             return [x, y, z]
         csp.define_problem(problem)
-        csp.print_state()
         csp = csp.clone()
         assert csp.ask() == 1
         assert csp.merge() == (1, 2, 3)

Modified: pypy/dist/pypy/objspace/constraint/test/test_constraint.py
==============================================================================
--- pypy/dist/pypy/objspace/constraint/test/test_constraint.py	(original)
+++ pypy/dist/pypy/objspace/constraint/test/test_constraint.py	Wed Apr 19 19:05:59 2006
@@ -16,6 +16,8 @@
         assert len(variables) == 2
         assert v1 in variables
         assert v2 in variables
+        assert cstr.knows_var(v1)
+        assert cstr.knows_var(v2)
 
     def test_estimated_cost(self):
         csp = newspace()

Modified: pypy/dist/pypy/objspace/constraint/test/test_distributor.py
==============================================================================
--- pypy/dist/pypy/objspace/constraint/test/test_distributor.py	(original)
+++ pypy/dist/pypy/objspace/constraint/test/test_distributor.py	Wed Apr 19 19:05:59 2006
@@ -22,6 +22,10 @@
         d = NaiveDistributor()
         d.distribute(spc, 2)
         assert spc.dom(y) == FiniteDomain([2])
+        d.distribute(spc, 1)
+        assert spc.dom(y) == FiniteDomain([2])
+        assert spc.dom(z) == FiniteDomain([1])
+        
 
     def test_split_distributor(self):
         spc = newspace()

Modified: pypy/dist/pypy/objspace/constraint/test/test_solver.py
==============================================================================
--- pypy/dist/pypy/objspace/constraint/test/test_solver.py	(original)
+++ pypy/dist/pypy/objspace/constraint/test/test_solver.py	Wed Apr 19 19:05:59 2006
@@ -21,10 +21,7 @@
         spc.define_problem(problems.conference_scheduling)
         
         sols = solver.solve(spc)
-        count = 0
         solutions = set()
         for sol in sols:
-            assert sol not in solutions
             solutions.add(sol)
-            count += 1
-        assert count == 64
+        assert len(solutions) == 64

Added: pypy/dist/pypy/objspace/constraint/util.py
==============================================================================
--- (empty file)
+++ pypy/dist/pypy/objspace/constraint/util.py	Wed Apr 19 19:05:59 2006
@@ -0,0 +1,37 @@
+
+def sort(l):
+    """in place merge sort"""
+    _sort(l, 0, len(l) - 1)
+
+def _sort(l, low, high):
+    if low >= high: return
+    mid = (low + high) / 2
+    _sort(l, low, mid)
+    _sort(l, mid + 1, high)
+    stop_low = mid
+    start_high = mid + 1
+    while low <= stop_low and start_high <= high:
+        if l[low] < l[start_high]:
+            low += 1
+        else:
+            t = l[start_high]
+            k = start_high - 1
+            while k >= low:
+                l[k+1] = l[k]
+                k -= 1
+            l[low] = t
+            low += 1
+            stop_low += 1
+            start_high += 1
+
+
+def reverse(l):
+    """reverse the content of a vector"""
+    length = len(l)
+    mid = length / 2
+    max = length - 1
+    idx = 0
+    while idx < mid:
+        antidx = max-idx
+        l[idx], l[antidx] = l[antidx], l[idx]
+        idx += 1



More information about the Pypy-commit mailing list