Skip to content

Instantly share code, notes, and snippets.

@jacob-faber
Created August 18, 2016 16:52
Show Gist options
  • Save jacob-faber/754115221b3884d8e8024a5671148d01 to your computer and use it in GitHub Desktop.
Save jacob-faber/754115221b3884d8e8024a5671148d01 to your computer and use it in GitHub Desktop.
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment