好久没写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 17
addens.
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 Falsebreakelse: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 = 0for j in range(0,len(lis_prime)):sumer = 0for i in range(j,len(lis_prime)):sumer = sumer + lis_prime[i]if sumer >= n :breakif (is_prime(sumer) is True) and (i-j >= maxlen):maxlen = i -jmaxsum = sumerlis1.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))
呜呜呜~~~所有的测试例子都能通过就是时间太长
蓝瘦香菇.。。。
本文链接:https://my.lmcjl.com/post/15940.html
4 评论