小编sar*_*eph的帖子

素数的生成器函数

我正在尝试编写一个生成函数来打印素数,如下所示

 def getPrimes(n):
    prime=True
    i=2
    while(i<n):
        for a in range(2,i):
            if(i%a==0):
                prime=False
                break
        if(prime):    
            yield i
Run Code Online (Sandbox Code Playgroud)

然而,我没有得到理想的结果p = getPrimes(100)应该给我一个生成器函数,它将从2到100迭代质数,但我得到的结果是[2,3].我究竟做错了什么?

python primes generator

4
推荐指数
2
解决办法
6083
查看次数

如何使基本的倒排索引程序更pythonic

我有一个反向索引的代码如下。但是我对它不太满意,并且想知道如何使它更紧凑和更pythonic

class invertedIndex(object):


  def __init__(self,docs):
     self.docs,self.termList,self.docLists=docs,[],[]

     for index,doc in enumerate(docs):

        for term in doc.split(" "):
            if term in self.termList:
                i=self.termList.index(term)
                if index not in self.docLists[i]:
                    self.docLists[i].append(index)

            else:
                self.termList.append(term)
                self.docLists.append([index])  

  def search(self,term):
        try:
            i=self.termList.index(term)
            return self.docLists[i]
        except:
            return "No results"





docs=["new home sales top forecasts june june june",
                     "home sales rise in july june",
                     "increase in home sales in july",
                     "july new home sales rise"]

i=invertedIndex(docs)
print invertedIndex.search("sales")
Run Code Online (Sandbox Code Playgroud)

python nlp machine-learning inverted-index

3
推荐指数
1
解决办法
830
查看次数