Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## itertools.combinations code, available here:http://docs.python.org/library/itertools.html#itertools.combinations
- def combinations(iterable, r):
- # combinations('ABCD', 2) --> AB AC AD BC BD CD
- # combinations(range(4), 3) --> 012 013 023 123
- pool = tuple(iterable)
- n = len(pool)
- if r > n:
- return
- indices = range(r)
- 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?
- while True:
- for i in reversed(range(r)):
- if indices[i] != i + n - r:
- break
- else: ## what's up with this syntax? shouldn't else be indented?
- return
- indices[i] += 1 ## is this still part of the for loop?
- for j in range(i+1, r):
- indices[j] = indices[j-1] + 1
- yield tuple(pool[i] for i in indices) ## why can't this go at the top of the for loop before everything else?
- ## my attempt
- def getCombinations(sortSub, size):
- """returns list with all ordered combinations of len(size)
- see itertools in python documation for more info"""
- # Note: itertools returns a tuple. Tuple not returned here
- # b/c yield function is not used
- combinations = []
- # Create tuple holding all letters of sortSub
- pool = tuple(sortSub)
- n = len(pool)
- # do nothing if len(pool) is less than the length of how long you
- # want the return tuples
- if size > n:
- return
- indices = range(size)
- newCombo = ""
- while True: ## this is how you make an infinite loop?
- for i in reversed(range(size)):
- # append string to combinations
- for x in indices:
- newCombo += pool[x]
- combinations.append(newCombo)
- newCombo = ""
- # Debug
- print "Latest combination =",combinations[-1]
- print "i:",i,"n:",n,"size:",size,"i + n - size =",i+n-size,"indices[i] =",indices[i],"indices =",indices
- if indices[i] == i + n - size: #
- return combinations
- indices[i] += 1
- for j in range(i+1, size):
- indices[j] = indices[j-1] + 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement