python - permutations with unique values -
itertools.permutations generates elements treated unique based on position, not on value. want avoid duplicates this:
>>> list(itertools.permutations([1, 1, 1])) [(1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1), (1, 1, 1)]
filtering afterwards not possible because amount of permutations large in case.
does know of suitable algorithm this?
thank much!
edit:
what want following:
x = itertools.product((0, 1, 'x'), repeat=x) x = sorted(x, key=functools.partial(count_elements, elem='x'))
which not possible because sorted
creates list , output of itertools.product large.
sorry, should have described actual problem.
class unique_element: def __init__(self,value,occurrences): self.value = value self.occurrences = occurrences def perm_unique(elements): eset=set(elements) listunique = [unique_element(i,elements.count(i)) in eset] u=len(elements) return perm_unique_helper(listunique,[0]*u,u-1) def perm_unique_helper(listunique,result_list,d): if d < 0: yield tuple(result_list) else: in listunique: if i.occurrences > 0: result_list[d]=i.value i.occurrences-=1 g in perm_unique_helper(listunique,result_list,d-1): yield g i.occurrences+=1 = list(perm_unique([1,1,2])) print(a)
result:
[(2, 1, 1), (1, 2, 1), (1, 1, 2)]
edit (how works):
i rewrite upper program longer more readable have hard time explain how works, let me try. in order understand how works have understand similar, simpler program yield permutations repetition.
def permutations_with_replecement(elements,n): return permutations_helper(elements,[0]*n,n-1)#this generator def permutations_helper(elements,result_list,d): if d<0: yield tuple(result_list) else: in elements: result_list[d]=i all_permutations = permutations_helper(elements,result_list,d-1)#this generator g in all_permutations: yield g
this program in simpler. d stands depth in permutations_helper , has 2 functions. 1 function stopping condition of our recursive algorithm , other result list, passed around.
instead of returning each result yield it. if there no function/operator yield
had push result in queue @ point of stopping condition. way once stopping condition meet result propagated trough stack caller. purpouse of
for g in perm_unique_helper(listunique,result_list,d-1): yield g
each result propagated caller.
back original program: have list of unique elements. before can use each element, have check how many of them still available push on result_list. working of program similar compared permutations_with_replecement
difference each element can not repeated more times in perm_unique_helper.
Comments
Post a Comment