Updated, look bottom!
I am stuck! I get a IndexError: list index out of range Error.
def makeInverseIndex(strlist):
numStrList = list(enumerate(strlist))
n = 0
m = 0
dictionary = {}
while (n < len(strList)-1):
while (m < len(strlist)-1):
if numStrList[n][1].split()[m] not in dictionary:
dictionary[numStrList[n][1].split()[m]] = {numStrList[n][0]}
m = m+1
elif {numStrList[n][0]} not in dictionary[numStrList[n][1].split()[m]]:
dictionary[numStrList[n][1].split()[m]]|{numStrList[n][0]}
m = m+1
n = n+1
return dictionary
it gives me this error
>>> makeInverseIndex(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "./inverse_index_lab.py", line 23, in makeInverseIndex
if numStrList[n][1].split()[m] not in dictionary:
IndexError: list index out of range
I don't get it... what causes this? It happens even when I change the conditions of the while loop. I don't get what is the problem. I am pretty new at this, so explain it like you would if a piece of broccoli asked you this question.
Edit:
Thanks guys, I forgot to mention examples of input, I want to input something like this:
L=['A B C', 'B C E', 'A E', 'C D A']
and get this as output:
D={'A':{0,2,3}, 'B':{0,1}, 'C':{0,3}, 'D':{3}, 'E':{1,2}}
so to create a dictionary that shows where in the list you might find a 'A' for example. It should work with a huge list. Do anyone have any tips? I want it to iterate and pick out each letter and then assign them a dictionary value.
Edit number two:
Thanks to great help from you guys my code looks beautiful like this:
def makeInverseIndex(strList):
numStrList = list(enumerate(strList))
n = 0
dictionary = {}
while (n < len(strList)):
for word in numStrList[n][1].split():
if word not in dictionary:
dictionary[word] = {numStrList[n][0]}
elif {numStrList[n][0]} not in dictionary[word]:
dictionary[word]|={numStrList[n][0]}
n = n+1
return dictionary
But I still manage to get this error when I try to run the module:
>>> makeInverseIndex(L)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "./inverse_index_lab.py", line 21, in makeInverseIndex
for word in numStrList[n][1].split():
NameError: global name 'StrList' is not defined
I do not see where the error can come from.
numStrList[n][1].split()[m]- you have three indexes here: n, 1, m - every one of them may cause this error - this behavior is fully depends on input data - check out what younumStrListcontains by justprint numStrList.StrListinwhile (n < len(StrList)-1):tostrlist