python-3.x 执行超时(12000ms),如何优化我的代码?[已关闭]

azpvetkf  于 2022-12-24  发布在  Python
关注(0)|答案(1)|浏览(143)

已关闭。此问题需要超过focused。当前不接受答案。
**想要改进此问题吗?**更新此问题,使其仅关注editing this post的一个问题。

3天前关闭。
Improve this question
我正试图解决一个Codewars形,代码工作良好的小数字,但与大数字运行太多,并在12秒后停止。代码必须返回[数量纯奇数位素数低于n,最大纯奇数位素数小于n,最小纯奇数位素数高于n]。我如何优化是运行速度更快?

def only_oddDigPrimes (n): # P.O.D.P (pure ood digit prime)
    prime, primeodd, result = [], [], []
    i = 2
    loop = True
    while loop:
        for j in range(2, i):
            if i % j == 0:
                break
        else:
            if i < n:
                for a in range(len(str(i))):
                    if int(str(i)[a]) % 2 == 0:
                        break
                else:
                    prime.append(i)
            if i > n:
                for b in range(len(str(i))):
                    if int(str(i)[b]) % 2 == 0:
                        break
                else:
                    result.append(i)  
                    loop = False
        i = i + 1
    
    
    for i in prime:
        if int(str(i)[0]) % 2 != 0 and i < n:
            primeodd.append(i)
    result.insert(0, primeodd[-1])
    result.insert(0, len(primeodd))
    print(result)
    
    return result
sdnqo3pr

sdnqo3pr1#

使用前面引用的Stackoverflow答案,我将这样解决这个问题:

import itertools

def erat():
    # function to implement sieve
    D = {}
    yield 2
    for q in itertools.islice(itertools.count(3), 0, None, 2):
        p = D.pop(q, None)
        if p is None:
            D[q * q] = q
            yield q
        else:
            x = p + q
            while x in D or not (x & 1):
                x += p
            D[x] = p

def get_primes(n: int) ->list:
    # function to list all primes less than or equal to n
    return list(itertools.takewhile(lambda p: p<=n, erat()))

def only_oddDigPrimes(n):
    # function to report on oddDigit Primes
    primes = get_primes(n*2)
    oddPrimes = []
    for pn in primes:
        add = True
        val = str(pn)
        for j in range(len(val)):
            if int(val[j]) % 2 == 0:
                add = False
                break
        if add:
            if pn > n:
                return [len(oddPrimes), oddPrimes[-1], pn]
            oddPrimes.append(pn)

相关问题