[Jython-checkins] jython: Add itertools.combinations_with_replacement

jim.baker jython-checkins at python.org
Thu Mar 15 21:51:04 CET 2012


http://hg.python.org/jython/rev/ed9a79f66dea
changeset:   6394:ed9a79f66dea
user:        Jim Baker <jbaker at zyasoft.com>
date:        Thu Mar 15 13:50:41 2012 -0700
summary:
  Add itertools.combinations_with_replacement

files:
  src/org/python/modules/itertools.java |  32 ++++++++++++++-
  1 files changed, 31 insertions(+), 1 deletions(-)


diff --git a/src/org/python/modules/itertools.java b/src/org/python/modules/itertools.java
--- a/src/org/python/modules/itertools.java
+++ b/src/org/python/modules/itertools.java
@@ -763,7 +763,37 @@
         };
     }
 
-//combinations_with_replacement(iterable, r):
+    public static PyIterator combinations_with_replacement(PyObject iterable, final int r) {
+        final PyTuple pool = PyTuple.fromIterable(iterable);
+        final int n = pool.__len__();
+        final int indices[] = new int[r];
+        for (int i = 0; i < r; i++) {
+            indices[i] = 0;
+        }
+
+        return new ItertoolsIterator() {
+            boolean firstthru = true;
+
+            @Override
+            public PyObject __iternext__() {
+                if (n == 0 || r == 0) {
+                    return null;
+                }
+                if (firstthru) {
+                    firstthru = false;
+                    return makeIndexedTuple(pool, indices);
+                }
+                int i;
+                for (i= r - 1 ; i >= 0 && indices[i] == n - 1; i--);
+                if (i < 0) return null;
+                indices[i]++;
+                for (int j = i + 1; j < r; j++) {
+                    indices[j] = indices[j-1];
+                }
+                return makeIndexedTuple(pool, indices);
+            }
+        };
+    }
 
     public static PyString __doc__compress = new PyString(
         "compress(data, selectors) --> iterator over selected data\n\n" +

-- 
Repository URL: http://hg.python.org/jython


More information about the Jython-checkins mailing list