-
Notifications
You must be signed in to change notification settings - Fork 11
/
heaps.py
54 lines (41 loc) · 981 Bytes
/
heaps.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
# implementation based on https://en.wikipedia.org/wiki/Heap%27s_algorithm
# Copyright Darío Clavijo 2024
from sympy import factorial
from sympy.combinatorics import Permutation
def heaps(k, A):
if k == 1:
yield A
else:
for i in range(0, k):
yield from heaps(k-1, A)
if k & 1 == 0:
A[i],A[k-1] = A[k-1],A[i]
else:
A[0],A[k-1] = A[k-1],A[0]
def heaps_count_swaps(k, A):
c = 0
if k == 1:
return 0
else:
for i in range(0, k):
c += heaps_count_swaps(k-1, A)
if k & 1 == 0:
A[i],A[k-1] = A[k-1],A[i]
else:
A[0],A[k-1] = A[k-1],A[0]
c += 1
return c
#A038156 = lambda n: heaps_count_swaps(n, list(range(0,n)))
def a(n):
m=0
L = list(range(0,n))
for p in heaps(len(L),L):
m = max(m,Permutation(p).rank())
return m
def a(n):
m=0
L = list(range(0,n))
for p in heaps(len(L),L):
m = Permutation(p).rank()
return m
print([a(n) for n in range(0,10)])