Add docstrings and doctests to combinations.py.
authorW. Trevor King <wking@drexel.edu>
Mon, 6 Dec 2010 20:47:25 +0000 (15:47 -0500)
committerW. Trevor King <wking@drexel.edu>
Tue, 7 Dec 2010 11:38:47 +0000 (06:38 -0500)
combinations.py

index 14251cfcc580683732a4ccba2e91eb723c55c0b9..987d6db214158b74e5ac2fbd1551da561593ce7b 100644 (file)
@@ -1,20 +1,57 @@
+"""Assorted useful combinatorics.
+"""
+
 from __future__ import generators
 
+
 def xcombinations(items, n):
+    """Iterate through ordered, length `n` subsets of `items`.
+
+    >>> for c in xcombinations([1, 2, 3], 2):
+    ...     print c
+    [1, 2]
+    [1, 3]
+    [2, 1]
+    [2, 3]
+    [3, 1]
+    [3, 2]
+    """
     if n==0: yield []
     else:
         for i in xrange(len(items)):
             for cc in xcombinations(items[:i]+items[i+1:],n-1):
                 yield [items[i]]+cc
 
-def xuniqueCombinations(items, n):
+def xunique_combinations(items, n):
+    """Iterate through unordered, length `n` subsets of `items`.
+
+    >>> for c in xunique_combinations([1, 2, 3], 2):
+    ...     print c
+    [1, 2]
+    [1, 3]
+    [2, 3]
+    """
     if n==0: yield []
     else:
         for i in xrange(len(items)):
-            for cc in xuniqueCombinations(items[i+1:],n-1):
+            for cc in xunique_combinations(items[i+1:],n-1):
                 yield [items[i]]+cc
-            
+
 def xselections(items, n):
+    """Iterate through all length `n` multisets of `items`.
+
+    >>> for c in xselections([1, 2, 3], 2):
+    ...     print c
+    [1, 1]
+    [1, 2]
+    [1, 3]
+    [2, 1]
+    [2, 2]
+    [2, 3]
+    [3, 1]
+    [3, 2]
+    [3, 3]
+    """
     if n==0: yield []
     else:
         for i in xrange(len(items)):
@@ -22,5 +59,16 @@ def xselections(items, n):
                 yield [items[i]]+ss
 
 def xpermutations(items):
+    """Iterate through all permutations of `items`.
+
+    >>> for c in xpermutations([1, 2, 3]):
+    ...     print c
+    [1, 2, 3]
+    [1, 3, 2]
+    [2, 1, 3]
+    [2, 3, 1]
+    [3, 1, 2]
+    [3, 2, 1]
+    """
     return xcombinations(items, len(items))