Ich mache gerade einen Onlinekurs (Linear Algebra through Computer Science Applications) und eine der Aufgaben für diese Woche lautet einen Inverse Index mit Hilfe von List Comprehensions zu schreiben. Bis auf ein kleines Problem funktioniert mein Code auch, ich weiß auch wo der Fehler steckt, aber ich probiere schon seit zwei Tagen ihn zu beheben, aber nichts will klappen. Verwendet wird Python 3.3.2
Code: Alles auswählen
def makeInverseIndex(strlist):
wordlist = [x for line in strlist for x in line.split()]
return {word:set{x for (x,y) in enumerate(strlist) if word in strlist[x]} for word in wordlist}
Code: Alles auswählen
>>> s = ['this is the first document',
'this is the second document',
'and this is a third document',
'perhaps there should be a fourth document',
'and now there is a fifth too']
>>> makeInverseIndex(s)
{'and': {2, 4}, 'a': {2, 3, 4}, 'now': {4}, 'third': {2}, 'be': {3}, 'this': {0, 1, 2}, 'is': {0, 1, 2, 4}, 'there': {3, 4}, 'should': {3}, 'perhaps': {3}, 'second': {1}, 'too': {4}, 'fourth': {3}, 'the': {0, 1, 3, 4}, 'document': {0, 1, 2, 3}, 'fifth': {4}, 'first': {0}}
z.B.:
Code: Alles auswählen
>>> s = ['dog', 'cat', 'dogs', 'cats']
>>> makeInverseIndex(s)
{'dogs': {2}, 'cats': {3}, 'dog': {0, 2}, 'cat': {1, 3}}
Vielen Dank im Vorraus,
Georgebaker