rougier / from-python-to-numpy

An open-access book on numpy vectorization techniques, Nicolas P. Rougier, 2017
http://www.labri.fr/perso/nrougier/from-python-to-numpy
Other
2.06k stars 340 forks source link

Bug in R"eadability vs speed" section #109

Closed zmunro closed 1 year ago

zmunro commented 1 year ago

The two functions listed as examples that are supposed to perform the same function are not the same.

def function_1(seq, sub):
    return [i for i in range(len(seq) - len(sub)) if seq[i:i+len(sub)] == sub]

def function_2(seq, sub):
    target = np.dot(sub, sub)
    candidates = np.where(np.correlate(seq, sub, mode='valid') == target)[0]
    check = candidates[:, np.newaxis] + np.arange(len(sub))
    mask = np.all((np.take(seq, check) == sub), axis=-1)
    return candidates[mask]

Example:

function_1([1,2,3,1,2], [1,2]) # output [0]
function_1([1,2,3,1,2], [1,2]) # output array([0, 3])

To fix the first function, it should be the following:

def function_1(seq, sub):
    return [i for i in range(len(seq) - len(sub) + 1) if seq[i:i+len(sub)] == sub]
zmunro commented 1 year ago

Actually, it looks like this has been changed in the repo, but the website does not have the most up to date version of the code.

rougier commented 1 year ago

Thanks for the report. I just updated all the files.