Skip to main content
 首页 » 编程设计

Python 3 : List of over 100 indices cycles back around after index 47. 为什么我该如何阻止呢

2025年02月15日13dflying

所以这是一个获取第n个质数的函数。我知道它以前已经完成,而且我的方法可能不是很有效(顺便说一句,新编码员过去曾有过少量涉猎)。 无论如何,下面的代码有效并返回所提供索引的质数。 即:

ind = 4 
final[1,2,3,5,7,11] 
return final[ind-1] 
returns: 5 

但是 final[51-1] 返回 final[3-1] 中的内容。似乎在索引 47 之后循环并重新开始。我打印了 final 中包含的整个列表。它会打印每个素数,甚至是 47 岁以后的素数。我不确定发生了什么。 python 中的列表有一些限制吗?

代码如下:

def nthPrime(ind): #gets nth prime number. IE: 5th prime == 11. works based off very in-efficient version of Sieve of Eratosthenes. but in increments of 200 
    p = {} 
    T = 2 
    incST = 2 
    incEND = incST + 200 
    final=[1] 
 
    while len(final) < ind: 
        for i in range(incST,incEND): 
            p[i] = True 
 
        while T <= math.sqrt(incEND): 
            l = 0 
            while l <= incEND: 
                p[T**2 + (T*l)] = False 
                l+=1 
                if T**2+(T*l) > incEND: 
                   break 
 
            for k,v in p.items(): 
                if p[k] == True and k > T: 
                    T = int(k) 
                    break 
 
        for k in p: 
            if p[k] == True: 
                final.append(k) 
 
        incST = incEND + 1 
        incEND = incST + 200 
 
    ''' 
    currently function works perfectly for 
    any index under 48. 
    at index 48 and above it seems to start 
    back at index 1. 
    IE: final[51] 
    ^would actually return final[4] 
    ''' 
 
 
    return final[ind-1] 

请您参考如下方法:

您需要计算您的列表中有多少个质数,但您在循环内的 final 中累积,因此您在循环中多次将所有数字加到极限。 199 后再次从 2 开始。

此外,使用字典和依赖顺序是危险的。您应该在迭代时对它们进行排序。

我的解决方案只计算素数以知道何时结束循环,并在最后组成列表,省略 1 并将索引移动 1。

我还在遍历字典时对字典进行排序,以确保:

import math 
 
def nthPrime(ind): #gets nth prime number. IE: 5th prime == 11. works based off very in-efficient version of Sieve of Eratosthenes. but in increments of 200 
    p = {} 
    T = 2 
    incST = 2 
    incEND = incST + 200 
 
    lenfinal = 1 
    while lenfinal < ind: 
        for i in range(incST,incEND): 
            p[i] = True 
 
        while T <= math.sqrt(incEND): 
            l = 0 
            while l <= incEND: 
                p[T**2 + (T*l)] = False 
                l+=1 
                if T**2+(T*l) > incEND: 
                   break 
 
            for k,v in sorted(p.items()): 
                if v and k > T: 
                    T = int(k) 
                    break 
 
 
        incST = incEND + 1 
        incEND = incST + 200 
        # compute length, no need to order or to actually create the list 
        lenfinal = sum(1 for k,v in p.items() if v) 
 
    # now compose the list 
    final = [k for k,v in sorted(p.items()) if v] 
 
    return final[ind-2]