小编Ton*_*nen的帖子

通过递推公式改进纯Python筛子

我试图通过取出子列表长度的复杂公式来进一步优化素数线程中的冠军解决方案.同一子序列的len()太慢,因为len很昂贵并且生成子序列很昂贵.这看起来稍微加快了功能,但我还是不能带走除法,尽管我只在条件语句中进行除法.当然,我可以尝试通过优化n的起始标记而不是n*n来简化长度计算...

我将division /整数除法//替换为与Python 3兼容

from __future__ import division
Run Code Online (Sandbox Code Playgroud)

如果这个递推公式可以帮助加速numpy解决方案,我会很有趣,但我没有经验使用numpy.

如果你为代码启用了psyco,那么故事会变得完全不同,而且Atkins筛选代码变得比这种特殊的切片技术更快.

import cProfile

def rwh_primes1(n):
    # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Returns  a list of primes < n """
    sieve = [True] * (n//2)
    for i in xrange(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = [False] * ((n-i*i-1)//(2*i)+1)
    return [2] + [2*i+1 for i in xrange(1,n/2) if sieve[i]]

def primes(n):
    # http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    # recurrence formula for length by amount1 and amount2 Tony Veijalainen 2010
    """ Returns  a list of primes < n """
    sieve = [True] * …
Run Code Online (Sandbox Code Playgroud)

python primes list slice

16
推荐指数
1
解决办法
2964
查看次数

转换为发电机3.4倍减速

怎么了?有人可以解释一下这里发生了什么,我在紧密循环中改变了:

##            j=i
##            while j < ls - 1 and len(wordlist[j]) > lc: j+=1
            j = next(j for j in range(i,ls) if len(wordlist[j]) <=  lc)
Run Code Online (Sandbox Code Playgroud)

评论的版本运行整个程序:625毫秒,下一个生成器版本2.125秒的时间内运行整个程序.

有什么理由可以说这个更加pythonic的版本会导致性能上的这种灾难?

编辑:也许它是由使用psyco模块引起的?当然至少没有psyco的Python 2.7的运行时间对于下一个版本来说是2.141,意味着与使用psyco的Python 2.6几乎相同.

删除*.pyc文件后,我得到的代码没有减速.然后,当我从库模块中删除了psyco的导入时,我还得到了2.6时序,没有psyco使用,非psyco版本和psyco版本的结果(现在库例程也慢了,它的时间也相关:)

不是psyco:

  1. while:库中准备:532毫秒,总运行时间2.625秒
  2. 下一篇:库中的准备:532毫秒,总运行时间(time.clock()):2.844秒(版本与xrange相同的壁时间)

Psyco是:

  1. while:库中准备:297毫秒,总运行时间:609 ... 675毫秒
  2. 下一篇:库中的准备:297毫秒,总运行时间:1.922秒(程序中无处不在的范围而不是xrange的版本:1.985秒)

在带有2GB RAM的WindowsXP AMD Sempron 3100+系统中运行.使用两个全局变量计算循环和调用:

    j=i
    callcount += 1
    while j < ls - 1 and len(wordlist[j]) > lc:
        j+=1
        loopcount += 1
Run Code Online (Sandbox Code Playgroud)

使用psyco进行测试输入的结果:

Finished in 625 ms
Loopcount: 78317 …
Run Code Online (Sandbox Code Playgroud)

python optimization performance generator while-loop

11
推荐指数
1
解决办法
1703
查看次数

屈服,直到产生所有需要的值,是否有办法使切片变得懒惰

当发电机没有完成值并且已经读取了所有需要的结果时,有没有办法停止屈服?我的意思是生成器在没有做StopIteration的情况下提供值.

例如,这永远不会停止:(已修订)

from random import randint
def devtrue():
    while True:
        yield True

answers=[False for _ in range(randint(100,100000))]
answers[::randint(3,19)]=devtrue()
print answers
Run Code Online (Sandbox Code Playgroud)

我找到了这段代码,但还不明白,在这种情况下如何应用它:http: //code.activestate.com/recipes/576585-lazy-recursive-generator-function/

python generator variable-assignment slice lazy-sequences

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

最好,有效的方法来获得序列项的结果元组满足和不满足条件

(这是专业的最佳实践/模式兴趣,而不是家庭工作要求)

  • INPUT:任何无序序列或生成器,函数myfilter(item)如果满足过滤条件则返回True

  • OUTPUT:(filter_true,filter_false)原始类型序列的元组,其包含按原始序列顺序根据过滤器分区的元素.

如果不进行双重过滤,你会如何表达这一点,还是应该使用双重过滤?也许filter和loop/generator/list comprehencion next可以回答?

我是否应该考虑保持类型或只是改变要求给出元组/发电机结果的元组,我不能轻易返回发电机输入发电机,或者我可以吗?(要求是自制的)

这里测试最佳候选人,提供两个流而不是元组

import itertools as it
from sympy.ntheory import isprime as myfilter

mylist = xrange(1000001,1010000,2)
left,right = it.tee((myfilter(x), x) for x in mylist)
filter_true = (x for p,x in left if p)
filter_false = (x for p,x in right if not p)

print 'Hundred primes and non-primes odd  numbers'
print  '\n'.join( " Prime %i, not prime %i" %
                  (next(filter_true),next(filter_false))
                  for i in range(100))
Run Code Online (Sandbox Code Playgroud)

python generator filter data-partitioning

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

使用这个setitem函数克服列表理解限制是否非常单一?

>>> a=range(5)
>>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects
[0, 2, 4]
>>> a
[0, 1, 2, 3, 4]
>>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment
SyntaxError: invalid syntax
>>> def setitem(listtochange,n,value):  ## function to overcome limitation
    listtochange[n]=value
    return value

>>> [setitem(a,i,'x') for i in range(0,len(a),2)] ## proving the function
['x', 'x', 'x']
>>> a 
['x', 1, 'x', 3, 'x']   # We did assignment anyway
Run Code Online (Sandbox Code Playgroud)

python list-comprehension side-effects variable-assignment

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

查找从关键字列表到dict的所有句子

我列出了可能的单词来制作给定单词的字谜.每个列表的字符串都是字典的关键,并且具有一个或多个单词的值.哪种是最好的(最快的,pythonic)方法,按照字典中相应键的每个列表中的单词的键的顺序来制作所有可能的句子.列表中包含可变数量的键.

keylist = ['key1', 'key2', 'key3']
worddict = {'key1': ['a','b','c'], 'key2':['d','e','f'], 'key3':['g','h','i']}
Run Code Online (Sandbox Code Playgroud)

预期结果(第一个键列表中的第一个单词,第二个键列表中的第二个单词,依此类推):

["a d g",
"a d h",
"a d i",
.....
"c f i"]
Run Code Online (Sandbox Code Playgroud)

python combinations dictionary cpu-word

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

doesPythonLikeCamels

Java风格的camelCase是Python的良好实践.我知道Capilized名称应该按照惯例保留给类名.根据好的风格,方法应该是小写字母,或者实际上我不太确定.是否有关于命名的PEP?

评论:

对不起,骆驼:),我从答案PEP8获悉,我的头衔实际上是正确称为混合大小写(大写版本是首字母大写)阅读PEP后,我知道,正常情况下少用功能命名下划线应使用方法也.

python convention naming case pep

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

为什么改变全局不会给出错误?

为什么在地球上Python允许在函数中更改不是全局声明的列表?

再 - 更新

numbers = []
num = 4

def add(n, thisnum=None):
    # changing global list without global declaration!
    numbers.append(n)
    if thisnum:
         num = thisnum
         print 'num assigned', thisnum
    ##numbers = ('one', 'two', 'three')
    ## adding this line makes error:
"""Traceback (most recent call last):
  File "J:\test\glob_vals.py", line 13, in <module>
    add(i)
  File "J:\test\glob_vals.py", line 6, in add
    numbers.append(n)
UnboundLocalError: local variable 'numbers' referenced before assignment
"""

for i in (1,2,3,564,234,23):
    add(i)

print numbers
add(10, thisnum= 19)
# no …
Run Code Online (Sandbox Code Playgroud)

python global list side-effects

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

如何将漂亮的打印模块扩展到表格?

我有漂亮的打印模块,我准备,因为我不高兴pprint模块生成zillion行的数字列表有一个列表列表.以下是我的模块的示例用法.

    >>> a=range(10)
    >>> a.insert(5,[range(i) for i in range(10)])
    >>> a
    [0, 1, 2, 3, 4, [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8]], 5, 6, 7, 8, 9]
    >>> import pretty
    >>> pretty.ppr(a,indent=6)

    [0, 1, 2, 3, 4, 
          [
            [], 
            [0], …
Run Code Online (Sandbox Code Playgroud)

python formatting generator

-1
推荐指数
1
解决办法
1272
查看次数