-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithm 1.19.py
60 lines (49 loc) · 1.45 KB
/
algorithm 1.19.py
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
51
52
53
54
55
56
57
58
59
60
def print_partition(block, n):
partition = [[] for _ in range(n + 1)]
for i in range(1, n + 1):
partition[block[i]].append(i)
partition = [p for p in partition if p]
for i in partition:
print("(", end="")
for element in i:
print(element, end="")
print(")", end=" ")
print()
def number_partitions(n):
block = [1] * (n + 1)
next = [0] * (n + 1)
prev = [0] * (n + 1)
moving_forward = [True] * (n + 1)
next[1] = 0
print_partition(block, n)
j = n
while j > 1:
k = block[j]
if moving_forward[j]:
if next[k] == 0:
next[k] = j
prev[j] = k
next[j] = 0
if next[k] > j:
prev[j] = k
next[j] = next[k]
prev[next[j]] = j
next[k] = j
block[j] = next[k]
else:
block[j] = prev[k]
if k == j:
if next[k] == 0:
next[prev[k]] = 0
else:
next[prev[k]] = next[k]
prev[next[k]] = prev[k]
print_partition(block, n)
j = n
while j > 1 and ((moving_forward[j] and block[j] == j)
or (not moving_forward[j] and block[j] == 1)):
moving_forward[j] = not moving_forward[j]
j -= 1
# Main function
if __name__ == "__main__":
number_partitions(4)