string - Simple python 2.7 code has some kind of issue: "'list' object has no attribute 'find'" -


the purpose of code return dictionary lists beginning index of substring in larger string.

ex. matchup(["a", "b, "c", "d"], "abc") return: {"a":0, "b":1, "c":2, "d":-1} (with -1 being default empty key)

the hint question find function can tell beginning index substring in string. correct syntax, right? have array of characters in strarray, , y substring searching for.

def matchup (strarray, word):     index ={}     x in strarray:         index [x]=-1     y in word:        x in index:            if y in strarray:               index [x]= strarray.find(y)      return index  

you need call word.find, not strarray.find.

def matchup (strarray, word):     index = {}     ch in strarray:         index[ch] = word.find(ch)  # <---     return index 

(no need use nested loop)

usage example:

>>> matchup(["a", "b", "c", "d"], "abc") {'a': 0, 'c': 2, 'b': 1, 'd': -1} 

Comments

Popular posts from this blog

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

jsf - "PropertyNotWritableException: Illegal Syntax for Set Operation" error when setting value in bean -

arrays - Algorithm to find ideal starting spot in a circle -