look_and_say



In [47]:
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'

import numpy as np

In [147]:
a = np.array([1,1])


Out[147]:
array([1, 1])

In [148]:
diff = np.ediff1d(a, 1, 1)


Out[148]:
array([1, 0, 1])

In [149]:
index = np.nonzero(diff)[0]


Out[149]:
array([0, 2])

In [150]:
counts = np.ediff1d(index)


Out[150]:
array([2])

In [151]:
vals = a[index[:-1]]


Out[151]:
array([1])

In [152]:
# best way to interleave arrays
# https://stackoverflow.com/questions/5347065/interweaving-two-numpy-arrays
b = np.empty((vals.size + counts.size,), dtype=vals.dtype)
b[0::2] = counts
b[1::2] = vals
b


Out[152]:
array([2, 1])

In [153]:
def look_and_say(a):
    diff = np.ediff1d(a, 1, 1)
    index = np.nonzero(diff)[0]
    counts = np.ediff1d(index)
    vals = a[index[:-1]]
    c = np.empty((vals.size + counts.size,), dtype=vals.dtype)
    c[0::2] = counts
    c[1::2] = vals
    return c

In [154]:
look_and_say(b)


Out[154]:
array([1, 2, 1, 1])

In [156]:
c = a
print(c)

for i in range(20):
    c = look_and_say(c)
    print(c)


[1 1]
[2 1]
[1 2 1 1]
[1 1 1 2 2 1]
[3 1 2 2 1 1]
[1 3 1 1 2 2 2 1]
[1 1 1 3 2 1 3 2 1 1]
[3 1 1 3 1 2 1 1 1 3 1 2 2 1]
[1 3 2 1 1 3 1 1 1 2 3 1 1 3 1 1 2 2 1 1]
[1 1 1 3 1 2 2 1 1 3 3 1 1 2 1 3 2 1 1 3 2 1 2 2 2 1]
[3 1 1 3 1 1 2 2 2 1 2 3 2 1 1 2 1 1 1 3 1 2 2 1 1 3 1 2 1 1 3 2 1 1]
[1 3 2 1 1 3 2 1 3 2 1 1 1 2 1 3 1 2 2 1 1 2 3 1 1 3 1 1 2 2 2 1 1 3 1 1 1
 2 2 1 1 3 1 2 2 1]
[1 1 1 3 1 2 2 1 1 3 1 2 1 1 1 3 1 2 3 1 1 2 1 1 1 3 1 1 2 2 2 1 1 2 1 3 2
 1 1 3 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