Skip to main content
 首页 » 编程设计

python之使用列表寻找解决方案

2025年05月04日32落叶无声

我正在尝试生成代码,该代码将首先在函数 perfectsq(p) 中找到 modulos p 下的所有完美正方形。

有了完美正方形的列表。我想找到方程 y^2=x^3+Ax+B 的所有解。为此,我使用 perfectsq(p) 中的列表来检查 m=x^3+Ax+B 是否在该列表中。谁能告诉我为什么这段代码无法编译?

def perfectsq(p): 
    x=[] 
    for i in range(1,p): 
        m=(i**2)%p 
        x.extend(m) 
        i+=1 
 
 
def ellipticpt(a, b, p): 
    x=perfectsq(p) 
    if 4*(a**3)+27*(b**2) != 0: 
        for i in range(0,p): 
            m=(i**3+a*i+b)%p 
            if m in x: 
                i=x.index(m)+1 
                print (m,i) 
                i+=1 
            else: 
                i+=1 
    else: 
        print "Error" 

请您参考如下方法:

perfectsq x.extend(m) TypeError: 'int' object is not iterable

您不能 .extend() 一个带有单个数字参数的列表,它用于用另一个列表扩展一个列表。请改用 .append() 添加到列表的末尾。

同样 perfectsq() 不返回任何东西

尝试:

def perfectsq(p): 
    x=[] 
    for i in range(1,p): 
        m=(i**2)%p 
        x.append(m) 
        i+=1 
    return x 
 
 
def ellipticpt(a, b, p): 
    x=perfectsq(p) 
    if 4*(a**3)+27*(b**2) != 0: 
        for i in range(0,p): 
            m=(i**3+a*i+b)%p 
            if m in x: 
                i=x.index(m)+1 
                print (m,i) 
                i+=1 
            else: 
                i+=1 
    else: 
        print "Error"