Домашнее задание просит нас написать некоторые функции, а именно orSearch
и andSearch
.Pythonic способ определения функции
"""
Input: an inverse index, as created by makeInverseIndex, and a list of words to query
Output: the set of document ids that contain _any_ of the specified words
Feel free to use a loop instead of a comprehension.
>>> idx = makeInverseIndex(['Johann Sebastian Bach', 'Johannes Brahms', 'Johann Strauss the Younger', 'Johann Strauss the Elder', ' Johann Christian Bach', 'Carl Philipp Emanuel Bach'])
>>> orSearch(idx, ['Bach','the'])
{0, 2, 3, 4, 5}
>>> orSearch(idx, ['Johann', 'Carl'])
{0, 2, 3, 4, 5}
"""
Учитывая выше документация orSearch
так же в andSearch
мы возвращаем только тот набор документации, который содержит все экземпляры списка запросов.
Можно предположить, что обратный индекс уже предоставлен. Пример обратного индекса для ['hello world','hello','hello cat','hellolot of cats']
является {'hello': {0, 1, 2}, 'cat': {2}, 'of': {3}, 'world': {0}, 'cats': {3}, 'hellolot': {3}}
Так что мой вопрос, я был в состоянии написать ни одного понимания строки для orSearch
метода задается
def orSearch(inverseIndex, query):
return {index for word in query if word in inverseIndex.keys() for index in inverseIndex[word]}
Но я не могу думать о наиболее питонический способ написания andSearch
. Я написал следующий код, он работает, но я предполагаю, что это не то, что вещий
def andSearch(inverseIndex, query):
if len(query) != 0:
result = inverseIndex[query[0]]
else:
result = set()
for word in query:
if word in inverseIndex.keys():
result = result & inverseIndex[word]
return result
Все предложения на более компактный код для andSearch
?
Я новичок в python, я не использовал 'any' и' all'. Я читал о них, но я не могу использовать их в контексте. – AbKDs