Skip to content

Instantly share code, notes, and snippets.

@MikhailRyazanov
Created September 12, 2018 06:04
Show Gist options
  • Save MikhailRyazanov/f6f87e4fb9bd03810ab013ce34a78cbf to your computer and use it in GitHub Desktop.
Save MikhailRyazanov/f6f87e4fb9bd03810ab013ce34a78cbf to your computer and use it in GitHub Desktop.
Caching in default arguments
# See
# https://stackoverflow.com/a/279592
# https://stackoverflow.com/a/9158327
from __future__ import print_function
def test(m, n, reg=0.0,
_prm=[None, None], _M=[None, None],
_reg=[None], _LR=[None, None]):
print('m = {}, n = {}, reg = {}'.format(m, n, reg))
if _prm != [m, n]:
print('Generating M...')
M1 = [i for i in range(m)]
M2 = [n - i for i in range(n)]
_prm[:] = [m, n]
_M[:] = [M1, M2]
_reg[:] = [None]
else:
print('Using M')
M1, M2 = _M
if _reg != [reg]:
print('Updating LR...')
L = [reg * x for x in M1]
R = [reg * x for x in M2]
_reg[:] = [reg]
_LR[:] = [L, R]
else:
print('Using LR')
L, R = _LR
print('M1 =', M1)
print('M2 =', M2)
print('L =', L)
print('R =', R)
print()
test(10, 8)
test(10, 8)
test(10, 8, 0.5)
test(10, 8, 0.5)
test(8, 8, 0.5)
m = 10, n = 8, reg = 0.0
Generating M...
Updating LR...
M1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
M2 = [8, 7, 6, 5, 4, 3, 2, 1]
L = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
R = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
m = 10, n = 8, reg = 0.0
Using M
Using LR
M1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
M2 = [8, 7, 6, 5, 4, 3, 2, 1]
L = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
R = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
m = 10, n = 8, reg = 0.5
Using M
Updating LR...
M1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
M2 = [8, 7, 6, 5, 4, 3, 2, 1]
L = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
R = [4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0, 0.5]
m = 10, n = 8, reg = 0.5
Using M
Using LR
M1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
M2 = [8, 7, 6, 5, 4, 3, 2, 1]
L = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5]
R = [4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0, 0.5]
m = 8, n = 8, reg = 0.5
Generating M...
Updating LR...
M1 = [0, 1, 2, 3, 4, 5, 6, 7]
M2 = [8, 7, 6, 5, 4, 3, 2, 1]
L = [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5]
R = [4.0, 3.5, 3.0, 2.5, 2.0, 1.5, 1.0, 0.5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment