-
Notifications
You must be signed in to change notification settings - Fork 6
/
fannkuch_redux_python.py
56 lines (51 loc) · 1.53 KB
/
fannkuch_redux_python.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
# The Computer Language Benchmarks Game
# http://shootout.alioth.debian.org/
# contributed by Isaac Gouy
# converted to Java by Oleg Mazurov
# converted to Python by Buck Golemon
# modified by Justin Peel
def fannkuch(n):
maxFlipsCount = 0
permSign = True
checksum = 0
perm1 = range(n)
count = perm1[:]
rxrange = xrange(2, n - 1)
nm = n - 1
while 1:
k = perm1[0]
if k:
perm = perm1[:]
flipsCount = 1
kk = perm[k]
while kk:
perm[:k+1] = perm[k::-1]
flipsCount += 1
k = kk
kk = perm[kk]
if maxFlipsCount < flipsCount:
maxFlipsCount = flipsCount
checksum += flipsCount if permSign else -flipsCount
# Use incremental change to generate another permutation
if permSign:
perm1[0],perm1[1] = perm1[1],perm1[0]
permSign = False
else:
perm1[1],perm1[2] = perm1[2],perm1[1]
permSign = True
for r in rxrange:
if count[r]:
break
count[r] = r
perm0 = perm1[0]
perm1[:r+1] = perm1[1:r+2]
perm1[r+1] = perm0
else:
r = nm
if not count[r]:
print( checksum )
return maxFlipsCount
count[r] -= 1
from sys import argv
n = int(argv[1])
print( "Pfannkuchen(%i) = %i" % (n, fannkuch(n)) )