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

2.2 Readability VS Speed #87

Open shashikiran-alloli opened 5 years ago

shashikiran-alloli commented 5 years ago

I'm facing issues with the below code -

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]

function_2('shasdefiran','def')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-69-3a3e84d6ff06> in <module>
----> 1 function_2('shasdefiran','def')

<ipython-input-64-dc47768a25a7> in function_2(seq, sub)
      1 def function_2(seq, sub):
----> 2     target = np.dot(sub, sub)
      3     candidates = np.where(np.correlate(seq, sub, mode='valid') == target)[0]
      4     check = candidates[:, np.newaxis] + np.arange(len(sub))
      5     mask = np.all((np.take(seq, check) == sub), axis=-1)

TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('<U3') dtype('<U3') dtype('<U3')

Please help me understand the issue with the above code.

rougier commented 5 years ago

Can you test only the np.dot(sub,sub) call ? (and give here how do you generate the sub)