The Primes as a Result of the Longest Consecutive Sum I

好久没写codewars,哎,颓废了好多天。今天一写一题就是一天最后还是timeout,尴尬至极,但是至少输出答案都能对,需要优化代码。

题目:

https://www.codewars.com/kata/the-primes-as-a-result-of-the-longest-consecutive-sum-i/train/python

 

The Primes as a Result of the Longest Consecutive Sum I

This kata is inspired on the problem #50 of the Project Euler.

The prime 41 is the result of the sum of many consecutive primes.

In fact, 2 + 3 + 5 + 7 + 11 + 13 = 41 , (6 addens)

Furthermore, the prime 41 is the prime below 100 (val_max) that has the longest chain of consecutive prime addens.

The prime with longest chain of addens for val_max = 500 is 499 with 17addens.

In fact: 3+5+7+11+13+17+19+23+29+31+37+41+43+47+53+59+61= 499

Find the function prime_maxlength_chain()(primeMaxlengthChain() javascript), that receives an argument val_max, the upper limit, all the found primes should be less than val_max and outputs this found prime.

Let's see some cases:

prime_maxlength_chain(100) == [41]
prime_maxlength_chain(500) == [499]

If we have more than one prime with these features, the function should output an array with the found primes sorted.

prime_maxlength_chain(499) == [379, 491]

Random Tests for val_max (valMax)

100 ≤ val_max ≤ 500.000

代码如下:


def is_prime(n):
    for i in range(2, n):
        if n % i == 0:
            return False
            break
    else:
        return True
'''
lis_prime = []
for i in range(2,50000):
        if is_prime(i) is True:
           lis_prime.append(i)
print(lis_prime)
'''

def prime_maxlength_chain(n):
    
    lis_prime = []
    for i in range(2,n):
        if is_prime(i) is True:
           lis_prime.append(i)
    
    #print(lis_prime,len(lis_prime))   
    lis = {}
    lis1 = []
    lis2 = []
    maxlen = 0
    for j in range(0,len(lis_prime)):
        sumer = 0
        for i in range(j,len(lis_prime)):
            sumer = sumer + lis_prime[i]
            if sumer >= n :break
            if (is_prime(sumer) is True) and (i-j >= maxlen):
                maxlen = i -j
                maxsum = sumer
        lis1.append([maxsum,maxlen])
    for i in range(len(lis1)):
        if lis1[i][1] == maxlen:
            lis2.append(lis1[i][0])
    #aiMove2 = max(lis1, key=lis1.get)
    #keys = [x for x,y in lis1.items() if y == lis1[aiMove2]]
    print(lis1)
    lis2 = set(lis2)
    return sorted(list(lis2))



 

呜呜呜~~~所有的测试例子都能通过就是时间太长

蓝瘦香菇.。。。

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值