Skip to content

Commit 65636ca

Browse files
committed
Revert cast, improved query function
Cast was not needed since the return value was already being cast. Query function changed to use heapq.nlargest() for simplicity
1 parent 43c2faf commit 65636ca

2 files changed

Lines changed: 9 additions & 7 deletions

File tree

grid.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,4 @@ def vector_clip(vector, lowest, highest):
4444
"""Return vector, except if any element is less than the corresponding
4545
value of lowest or more than the corresponding value of highest, clip to
4646
those values."""
47-
return type(vector)(list(map(clip, vector, lowest, highest)))
47+
return type(vector)(map(clip, vector, lowest, highest))

text.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -147,15 +147,17 @@ def query(self, query_text, n=10):
147147
qwords = [w for w in words(query_text) if w not in self.stopwords]
148148
shortest = argmin(qwords, lambda w: len(self.index[w]))
149149
docs = self.index[shortest]
150-
results = sorted([(sum([self.score(w, d) for w in qwords]), d) for d in docs])
151-
results.reverse()
152-
return results[:n]
150+
return heapq.nlargest(n, ((total_score(qwords, doc), doc) for doc in docs))
153151

154-
def score(self, word, docid):
152+
def score(self, word, doc):
155153
"Compute a score for this word on this docid."
156154
# There are many options; here we take a very simple approach
157-
return (math.log(1 + self.index[word][docid]) /
158-
math.log(1 + self.documents[docid].nwords))
155+
return (math.log(1 + self.index[word][doc]) /
156+
math.log(1 + self.documents[doc].nwords))
157+
158+
def total_score(qwords, doc):
159+
"Compute the sum of the scores of the queried words on this doc."
160+
return sum(self.score(qword, doc) for qword in qwords)
159161

160162
def present(self, results):
161163
"Present the results as a list."

0 commit comments

Comments
 (0)