python视窗编程_python – 关于滑动窗口和memoization的计算

我正在研究Project Euler Problem 50,它指出:

The prime 41,can be written as the sum of six consecutive primes:

41 = 2 + 3 + 5 + 7 + 11 + 13

This is the longest sum of consecutive primes that adds to a prime below one-hundred.

The longest sum of consecutive primes below one-thousand that adds to a prime,contains 21 terms,and is equal to 953.

Which prime,below one-million,can be written as the sum of the most consecutive primes?

为了确定素数P中的项(如果它可以写成素数的总和),我使用所有素数的滑动窗口(按递增顺序)直到(但不包括)P,并计算所有的总和这些窗口,如果总和等于考虑的素数,我算一下窗口的长度……

这适用于1000以下的所有素数,但是对于高达10 ** 6的素数来说它非常慢,所以我希望备忘录会有所帮助;在计算滑动窗口的总和时,做了很多双重工作……(对吧?)

所以我在网上找到了标准的memoizaton实现,并将其粘贴在我的代码中,这是正确的吗? (我不知道应该怎么在这里工作……)

primes = tuple(n for n in range(1,10**6) if is_prime(n)==True)

count_best = 0

##http://docs.python.org/release/2.3.5/lib/itertools-example.html:

## Slightly modified (first for loop)

from itertools import islice

def window(seq):

for n in range(2,len(seq) + 1):

it = iter(seq)

result = tuple(islice(it,n))

if len(result) == n:

yield result

for elem in it:

result = result[1:] + (elem,)

yield result

def memoize(function):

cache = {}

def decorated_function(*args):

if args in cache:

return cache[args]

else:

val = function(*args)

cache[args] = val

return val

return decorated_function

@memoize

def find_lin_comb(prime):

global count_best

for windows in window(primes[0 : primes.index(prime)]):

if sum(windows) == prime and len(windows) > count_best:

count_best = len(windows)

print('Prime: ',prime,'Terms: ',count_best)

##Find them:

for x in primes[::-1]: find_lin_comb(x)

(顺便说一句,素数的元组是“正常”快速生成的)

所有的输入都很受欢迎,我只是一个业余爱好程序员,所以请不要对我有所了解.

谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值