Pythonic定义函数的方法

时间:2015-02-18 06:21:32

标签: python

家庭作业要求我们编写一些函数,即orSearchandSearch

"""
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}
"""

上面给出了orSearchandSearch类似的文档,我们只返回那些包含查询列表的所有实例的文档集。

我们可以假设已经提供了反向索引。 ['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的最抒情方式。我写了下面的代码,它可以工作,但我想这不是pythonic

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 个答案:

答案 0 :(得分:2)

重写orSearch()以使用any()查找任何字词,然后通过修改您的解决方案来使用andSearch()来查找所有字词,从而导出all()

答案 1 :(得分:1)

更多Pythonic写和Serch()的方法是:

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

这里我们使用reduce函数来聚合过渡计算的结果。

另外,检查查询的所有项目是否都在 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
相关问题