Last active
August 29, 2015 14:14
-
-
Save matsub/08cc0f586296898e99a5 to your computer and use it in GitHub Desktop.
associated to my blog: http://matsub.hatenablog.com/entry/2015/01/30/185724
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# codin: utf-8 | |
# memoizing decorator | |
def memoize(function): | |
def _memoize(*args, _cache={}): | |
if args in _cache: | |
print('return using cached') # just for logging | |
return _cache[args] | |
result = function(*args) | |
_cache[args] = result | |
print('memoized', args) # jsut for logging | |
return result | |
return _memoize | |
if __name__ == '__main__': | |
# compute modular exponentiation | |
@memoize | |
def pmod(base, exponent, mod): | |
n = 1 | |
while exponent: | |
if exponent & 1: | |
n = (n*base) % mod | |
exponent >>= 1 | |
base = (base**2) % mod | |
return n | |
# determine n is a probable prime or not | |
@memoize | |
def is_pseudoprime(n): | |
industrial_grade = (2, 3, 5, 7) | |
if n in industrial_grade: | |
return True | |
for base in industrial_grade: | |
if pmod(base, n-1, n) != 1: | |
return False | |
return True | |
# confirm that the cache has goodbye on another decorated | |
@memoize | |
def square(n): | |
return n**2 | |
print('>>> is 2 a prime number?') | |
print(is_pseudoprime(2)) | |
print('>>> really?') | |
print(is_pseudoprime(2)) | |
print('>>> okay then, the square of 2 is what?') | |
print(square(2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment