2015-02-18 6 views
0

Домашнее задание просит нас написать некоторые функции, а именно 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?

ответ

2

Rewrite orSearch() использовать any(), чтобы найти какие-либо из условий, а затем получить andSearch() путем изменения решения использовать all() вместо того, чтобы найти все условия.

+0

Я новичок в python, я не использовал 'any' и' all'. Я читал о них, но я не могу использовать их в контексте. – AbKDs

1

Более Pythonic способ написать andSerch() будет:

from functools import reduce 
def andSearch(inverseIndex, query): 
    return reduce(lambda x, y: x & y, [(inverseIndex[key]) for key in query]) 

Здесь мы использовали функцию снижения для агрегирования результатов переходных расчетов.

Также это может быть полезно, чтобы проверить, если все элементы запроса в inverseIndex. Тогда наша функция будет выглядеть так:

from functools import reduce 
def andSearch(inverseIndex, query): 
    if set(query) < set(inverseIndex.keys()): 
     return reduce(lambda x, y: x & y, [(inverseIndex[key]) for key in query]) 
    else: 
     return False # or what ever is meaningful to return 
Смежные вопросы