# # combopermute.py

May 1st, 2021
664
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. # combopermute.py
2.
3. def combinations(iterable, r):
4.     pool = tuple(iterable)
5.     n = len(pool)
6.     if r > n:
7.         return
8.     indices = list(range(r))
9.     yield tuple(pool[i] for i in indices)
10.     while True:
11.         for i in reversed(range(r)):
12.             if indices[i] != i + n - r:
13.                 break
14.         else:
15.             return
16.         indices[i] += 1
17.         for j in range(i+1, r):
18.             indices[j] = indices[j-1] + 1
19.         yield tuple(pool[i] for i in indices)
20.
21. def all_perms(elements):
22.     if len(elements) <=1:
23.         yield elements
24.     else:
25.         for perm in all_perms(elements[1:]):
26.             for i in range(len(elements)):
27.                 yield perm[:i] + elements[0:1] + perm[i:]
28.
29. results = []
30. l = [1,2,3,9]
31. n = 3
32. for i in combinations(l, n):
33.     for j in all_perms(i):
34.         results.append(j)
35.
36. results.sort()
37. for z in results:
38.     print z
39.
40. (1, 2, 3)
41. (1, 2, 9)
42. (1, 3, 2)
43. (1, 3, 9)
44. (1, 9, 2)
45. (1, 9, 3)
46. (2, 1, 3)
47. (2, 1, 9)
48. (2, 3, 1)
49. (2, 3, 9)
50. (2, 9, 1)
51. (2, 9, 3)
52. (3, 1, 2)
53. (3, 1, 9)
54. (3, 2, 1)
55. (3, 2, 9)
56. (3, 9, 1)
57. (3, 9, 2)
58. (9, 1, 2)
59. (9, 1, 3)
60. (9, 2, 1)
61. (9, 2, 3)
62. (9, 3, 1)
63. (9, 3, 2)
RAW Paste Data