grilam14 grilam14 - 26 days ago 8
Python Question

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

The purpose of this code is to return a dictionary that lists the beginning index of a substring in a larger string.

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

The hint for this question is that the find function can tell you the beginning index for a substring in another string. This is the correct syntax, right? I have my array of characters in strArray, and y is the substring I am searching for.

def matchUp (strArray, word):
index ={}
for x in strArray:
index [x]=-1
for y in word:
for x in index:
if y in strArray:
index [x]= strArray.find(y)

return index

Answer

You need to call word.find, not strArray.find.

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

(No need to use nested loop)

Usage example:

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