-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYourCombinations.py
More file actions
50 lines (39 loc) · 1.21 KB
/
Copy pathYourCombinations.py
File metadata and controls
50 lines (39 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#
# Author: Max Base
# Date: 2022/10/26
# Repository: https://github.com/BaseMax/YourCombinationsPython
#
class YourCombinations:
def __init__(self, elements):
self.elements = elements
self.count_elements = len(elements)
def powerSet(self):
size = 2 ** self.count_elements
for i in range(size):
cur = []
for j in range(self.count_elements):
if (i & (1 << j)) > 0:
cur.append(self.elements[j])
yield cur
def combinations(self, length, with_repetition = False, position = 0, elements = []):
size = len(self.elements)
for i in range(position, size):
elements.append(self.elements[i])
if len(elements) == length:
yield elements
else:
yield from self.combinations(length, with_repetition, (i + 1) if with_repetition == False else i, elements)
elements.pop()
def permutations(self, length, with_repetition = False, elements = [], keys = []):
for key, value in enumerate(self.elements):
if with_repetition == False:
if key in keys:
continue
keys.append(key)
elements.append(value)
if len(elements) == length:
yield elements
else:
yield from self.permutations(length, with_repetition, elements, keys)
keys.pop()
elements.pop()