1 # The Computer Language Shootout 2 # http://shootout.alioth.debian.org/ 3 # 4 # Contributed by Sokolov Yura 5 6 from sys import argv 7 def fannkuch(n): 8 count = range(1,n+1) 9 maxFlipsCount, m, r, check = 0, n-1, n, 0 10 11 perm1 = range(n) 12 perm = range(n) 13 perm1_ins = perm1.insert 14 perm1_pop = perm1.pop 15 while True: 16 if check < 30: 17 print "".join(`i+1` for i in perm1) 18 check += 1; 19 20 while r != 1: 21 count[r-1] = r 22 r -= 1 23 24 if perm1[0] != 0 and perm1[m] != m: 25 perm[:]=perm1 26 flipsCount = 0 27 k = perm[0] 28 while k: 29 perm[:k+1] = perm[k::-1] 30 flipsCount += 1 31 k = perm[0] 32 33 if flipsCount > maxFlipsCount: 34 maxFlipsCount = flipsCount 35 maxPerm = list(perm1) 36 37 while True: 38 if r == n: return maxFlipsCount 39 perm1_ins(r,perm1_pop(0)) 40 count[r] -= 1 41 if count[r] > 0: break 42 r += 1 43 44 def main(): 45 n = int(argv and argv[1] or 1) 46 print "Pfannkuchen(%d) = %d\n"%(n,fannkuch(n)), 47 48 if __name__=="__main__": 49 main()