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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import time
class DuplicateStdout:
def __init__ (self, file_object):
self.stdout = sys.stdout
self.clone = file_object
# end def
def write (self, message):
self.stdout.write(message)
self.clone.write(message)
# end def
def flush (self):
self.stdout.flush()
self.clone.flush()
# end def
def reset (self):
sys.stdout = self.stdout
# end def
# end class
# practical example with a Fibonacci's series study
def fibonacci (n):
"""
computing a Fibonacci's series item located at index @n;
"""
n = int(n)
if n < 0:
raise IndexError("Fibonacci series starts at index 0")
else:
a, b = 0, 1
for i in range(n):
a, b = b, a + b
# end for
return a
# end if
# end def
with open("fibonacci_dump.txt", "w") as file_out:
# duplicate stdout into a log file
sys.stdout = DuplicateStdout(file_out)
# send messages to both stdout and file_out
print("Searching mathematical laws in Fibonacci's series")
print("Looking to digits count of fibo(n) result numbers...")
for y in range(2, 11):
print("\nbase =", y, "\n")
for x in range(6):
n = y * 10**x
start = time.perf_counter()
result = str(fibonacci(n))
print(
"{:20s}{:24s}{}".format(
"fibo({})".format(n),
"has {} digits".format(len(result)),
"computed in {:.8f} sec"
.format(time.perf_counter() - start),
)
)
# end for
# end for
# return to genuine stdout
sys.stdout.reset()
# end with
print("\nDone. OK.") |
Partager