繁体   English   中英

Python列表索引错误

[英]Python List Indexing Error

def getPrimeList(check):
    storedprimes = []
    i = 2
    while i <= check:
        if isPrime(check):
            storedprimes = storedprimes + [i]
        i = i + 1
    return storedprimes
def getPrimeFact(check):
    primelist = getPrimeList(check)
    prime_fact = []
    i = 0
    while check !=1:
        if check%primelist[i]==0:
            prime_fact=prime_fact+[primelist[i]]
            check = check/primelist[i]
        i = i + 1
        if i == len(primelist):
            i = 0
    return prime_fact
def getGCF(checks):
    a=0
    listofprimefacts=[]
    while a<len(checks):
        listofprimefacts=listofprimefacts+[getPrimeFact(checks[a])]
        a=a+1
    b=0
    storedprimes=[]
    while b<len(primefactlist):
        c=0
        while c<len(listofprimefacts[b]):
            if listofprimefacts[b][c] not in storedprimes:
                storedprimes=storedprimes+[listofprimefacts[b][c]]
            c=c+1
        b=b+1
    prime_exp=[]
    d=0
    while d<len(storedprimes):
        prime_exp=prime_exp+[0]
        d=d+1

    e=0
    while e<len(storedprimes):
        f=0
        while f<len(listofprimefacts):
            if f==0:
                prime_exp[e]=listofprimefacts[f].count(storedprimes[e])
            elif prime_exp[e]-(listofprimefacts[f].count(storedprimes[e]))>0:
                prime_exp[e]=listofprimefacts[f].count(storedprimes[e])                
            f=f+1
        e=e+1
    g=0
    GCF=1
    while g<len(primelist):
        GCF=GCF*(storedprime[g]**prime_exp[g])
        g=g+1
    return GCF

我正在创建一个程序,这些程序将使用这些功能来计算分数。 但是,在外壳中测试了我的GCF函数之后,我不断收到列表索引错误。 我不知道,错误出在哪里是因为我认为99%的索引没有问题,通常我不会在SO中发布这样的“可修复”问题,但是这次我只是不知道问题是什么,再次感谢。

哦,这是确切的错误

File "<pyshell#1>", line 1, in <module>
    getGCF(checks)
  File "E:\CompProgramming\MidtermFuncts.py", line 31, in getGCF
    listofprimefacts=listofprimefacts+[getPrimeFact(checks[a])]
  File "E:\CompProgramming\MidtermFuncts.py", line 20, in getPrimeFact
    if check%primelist[i]==0:
IndexError: list index out of range

您可能需要重新考虑如何解决此问题。 在当前形式下,您的代码确实很难使用。

这是我的处理方式:

def is_prime(n):
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False

    return True

def prime_factors(number):
    factors = []

    for i in range(2, number / 2):
        if number % i == 0 and is_prime(i):
            factors.append(i)

    return factors

def gcf(numbers):
    common_factors = prime_factors(numbers[0])

    for number in numbers[1:]:
        new_factors = prime_factors(number)
        common_factors = [factor for factor in common_factors if factor in new_factors]

    return max(common_factors)

这行就在这里:

common_factors = [factor for factor in common_factors if factor in new_factors]

是列表理解。 您可以将其展开到另一个for循环中:

temp = []

for factor in common_factors:
    if factor in new_factors:
        temp.append(factor)

common_factors = list(temp)  # Pass by value, not by reference

您混合了icheck入了getPrimeList()函数; 您测试check是否是质数, 而不是 i 这是正确的功能:

def getPrimeList(check):
    storedprimes = []
    i = 2
    while i <= check:
        if isPrime(i):  # *not* `check`! 
            storedprimes = storedprimes + [i]
        i = i + 1
    return storedprimes

primelist将被设置为一个空列表(因为getPrimeList(check)返回一个空列表),并且您的primelist[i] (对于任何 i )将失败,并出现索引错误。

primelist为空的另一种方式是,当primelist isPrime()从不返回True时; 您没有向我们展示该功能来进行验证。

您的下一个错误是在getGCF() 您首先定义一个listofprimefacts变量(一个列表),但随后引用一个不存在的primefactlist变量,导致一个NameError 下一个名称错误将在该函数中进一步成为primelist

您确实想重新阅读Python教程 您在代码中错过了许多python习语; 特别是关于如何在序列上创建循环(提示: for check in checks:比带有索引变量的while循环更易于使用)以及如何将项目附加到列表中。

我的个人工具包对此进行了定义:

from math import sqrt

def prime_factors(num, start=2):
    """Return all prime factors (ordered) of num in a list"""
    candidates = xrange(start, int(sqrt(num)) + 1)
    factor = next((x for x in candidates if (num % x == 0)), None)
    return ([factor] + prime_factors(num / factor, factor) if factor else [num])

不需要isPrime()测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM