camabeh
8/18/2016 - 4:52 PM

lru_cache

lru_cache

from functools import lru_cache

# Without cache:
#  User time (seconds): 29.46
#  Maximum resident set size (kbytes): 9724

# With cache:
#  User time (seconds): 2.34
#  Maximum resident set size (kbytes): 297288
#  CacheInfo(hits=999998, misses=2168611, maxsize=None, currsize=2168611)


@lru_cache(maxsize=None)
def solution(num):
    if num == 1:
        return 1
    elif num % 2 == 0:
        return solution(num // 2)
    else:
        return solution(3 * num + 1)


def run(start, stop):
    for num in range(start, stop):
        solution(num)
    print(solution.cache_info())

def main():
    run(1, 10 ** 6)


if __name__ == '__main__':
    main()