Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # combopermute.py
- def combinations(iterable, r):
- pool = tuple(iterable)
- n = len(pool)
- if r > n:
- return
- indices = list(range(r))
- yield tuple(pool[i] for i in indices)
- while True:
- for i in reversed(range(r)):
- if indices[i] != i + n - r:
- break
- else:
- return
- indices[i] += 1
- for j in range(i+1, r):
- indices[j] = indices[j-1] + 1
- yield tuple(pool[i] for i in indices)
- def all_perms(elements):
- if len(elements) <=1:
- yield elements
- else:
- for perm in all_perms(elements[1:]):
- for i in range(len(elements)):
- yield perm[:i] + elements[0:1] + perm[i:]
- def combopermute(l, n):
- for i in combinations(l, n):
- for j in all_perms(i):
- yield j
- # speed demonstration
- l = [1,2,3,9]
- n = 3
- test = combopermute(l, n)
- for t in test:
- print(t)
- (1, 2, 3)
- (2, 1, 3)
- (2, 3, 1)
- (1, 3, 2)
- (3, 1, 2)
- (3, 2, 1)
- (1, 2, 9)
- (2, 1, 9)
- (2, 9, 1)
- (1, 9, 2)
- (9, 1, 2)
- (9, 2, 1)
- (1, 3, 9)
- (3, 1, 9)
- (3, 9, 1)
- (1, 9, 3)
- (9, 1, 3)
- (9, 3, 1)
- (2, 3, 9)
- (3, 2, 9)
- (3, 9, 2)
- (2, 9, 3)
- (9, 2, 3)
- (9, 3, 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement