| 1 |
|
| 2 |
""" |
| 3 |
The Computer Language Benchmarks Game |
| 4 |
http://benchmarksgame.alioth.debian.org/ |
| 5 |
|
| 6 |
Contributed by Sokolov Yura, modified by Tupteq. |
| 7 |
""" |
| 8 |
|
| 9 |
import pyperf |
| 10 |
import time |
| 11 |
|
| 12 |
DEFAULT_ARG = 10 |
| 13 |
|
| 14 |
|
| 15 |
def fannkuch(n): |
| 16 |
count = list(range(1, n + 1)) |
| 17 |
max_flips = 0 |
| 18 |
m = n - 1 |
| 19 |
r = n |
| 20 |
perm1 = list(range(n)) |
| 21 |
perm = list(range(n)) |
| 22 |
perm1_ins = perm1.insert |
| 23 |
perm1_pop = perm1.pop |
| 24 |
|
| 25 |
while 1: |
| 26 |
while r != 1: |
| 27 |
count[r - 1] = r |
| 28 |
r -= 1 |
| 29 |
|
| 30 |
if perm1[0] != 0 and perm1[m] != m: |
| 31 |
perm = perm1[:] |
| 32 |
flips_count = 0 |
| 33 |
k = perm[0] |
| 34 |
while k: |
| 35 |
perm[: k + 1] = perm[k::-1] |
| 36 |
flips_count += 1 |
| 37 |
k = perm[0] |
| 38 |
|
| 39 |
if flips_count > max_flips: |
| 40 |
max_flips = flips_count |
| 41 |
|
| 42 |
while r != n: |
| 43 |
perm1_ins(r, perm1_pop(0)) |
| 44 |
count[r] -= 1 |
| 45 |
if count[r] > 0: |
| 46 |
break |
| 47 |
r += 1 |
| 48 |
else: |
| 49 |
return max_flips |
| 50 |
|
| 51 |
|
| 52 |
if __name__ == "__main__": |
| 53 |
|
| 54 |
arg = DEFAULT_ARG |
| 55 |
start_p = time.perf_counter() |
| 56 |
|
| 57 |
for i in range(3): |
| 58 |
fannkuch(arg) |
| 59 |
stop_p = time.perf_counter() |
| 60 |
|
| 61 |
print("Time elapsed: ", stop_p - start_p) |