Advertisement
Asix3

MIT Pset6

Feb 2nd, 2012
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.19 KB | None | 0 0
  1. ## itertools.combinations code, available here:http://docs.python.org/library/itertools.html#itertools.combinations
  2.  
  3. def combinations(iterable, r):
  4.     # combinations('ABCD', 2) --> AB AC AD BC BD CD
  5.     # combinations(range(4), 3) --> 012 013 023 123
  6.     pool = tuple(iterable)
  7.     n = len(pool)
  8.     if r > n:
  9.         return
  10.     indices = range(r)
  11.     yield tuple(pool[i] for i in indices) ## seems like this is just adding the first combo -- why can't it be inside the for loop?
  12.     while True:
  13.         for i in reversed(range(r)):
  14.             if indices[i] != i + n - r:
  15.                 break
  16.         else: ## what's up with this syntax? shouldn't else be indented?
  17.             return
  18.         indices[i] += 1 ## is this still part of the for loop?
  19.         for j in range(i+1, r):
  20.             indices[j] = indices[j-1] + 1
  21.         yield tuple(pool[i] for i in indices) ## why can't this go at the top of the for loop before everything else?
  22.  
  23. ## my attempt
  24.  
  25. def getCombinations(sortSub, size):
  26.     """returns list with all ordered combinations of len(size)
  27.    see itertools in python documation for more info"""
  28.     # Note: itertools returns a tuple. Tuple not returned here
  29.     # b/c yield function is not used
  30.     combinations = []
  31.     # Create tuple holding all letters of sortSub
  32.     pool = tuple(sortSub)
  33.    
  34.     n = len(pool)
  35.  
  36.     # do nothing if len(pool) is less than the length of how long you
  37.     # want the return tuples
  38.     if size > n:
  39.         return
  40.  
  41.     indices = range(size)
  42.  
  43.     newCombo = ""
  44.     while True: ## this is how you make an infinite loop?
  45.         for i in reversed(range(size)):
  46.  
  47.             # append string to combinations
  48.             for x in indices:
  49.                 newCombo += pool[x]
  50.             combinations.append(newCombo)
  51.             newCombo = ""
  52.  
  53.             # Debug
  54.             print "Latest combination =",combinations[-1]
  55.             print "i:",i,"n:",n,"size:",size,"i + n - size =",i+n-size,"indices[i] =",indices[i],"indices =",indices
  56.  
  57.             if indices[i] == i + n - size: #
  58.                 return combinations
  59.             indices[i] += 1
  60.             for j in range(i+1, size):
  61.                 indices[j] = indices[j-1] + 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement