from time import time, sleepdef running_time(func):""" 関数の実行時間(秒)を有効桁小数点3桁で表示して、元の関数の戻り値を返すデコレータ """def wrapper(*args, **kwargs): start = time() result = func(*args, **kwargs) end = time() elapsed = end - startprint(f"Execution time: {elapsed:.3f} seconds")return resultreturn wrapper
Example 1カントールの対関数の逆関数と実行時間計算
Code
import numpy as np@running_timedef compute_contor_inverse(J: int):"""Compute the inverse of the Cantor pairing function. The Cantor pairing function maps pairs of natural numbers to single natural numbers. This function computes the inverse mapping, taking a natural number and returning the original pair of numbers. Args: J (int): A natural number that was produced by the Cantor pairing function. Must be non-negative. Returns: tuple[int, int]: A pair (x, y) of numbers such that their Cantor pairing would produce J. The first element x represents the first number in the original pair, and y represents the second number. """ t =int((np.sqrt(1+8* J) -1) //2) x = (t **3+3* t) //2- J y = J - (t **2+ t) //2return x, youtput = compute_contor_inverse(100)print(output)