“for item in L”循环中的语法无效

2024-06-30 16:21:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一种感觉,我在这里遗漏了一些非常简单的东西,但是,在这个函数中:

def triplets(perimeter):

    triplets, n, a, b, c = 0  #number of triplets, a, b, c, sides of a triangle, n is used to calculate a triple
    L = primes(int(math.sqrt(perimeter)) #list of primes to divide the perimeter

    for item in L: #iterate through the list of primes
        if perimeter % item == 0: #check if a prime divides the perimeter
            n = perimeter / item
            a = n**2 - (n+1)**2 #http://en.wikipedia.org/wiki/Pythagorean_triple
            b = 2n*(n+1)
            c = n**2 + n**2
            if a+b+c == perimeter: #check if it adds up to the perimeter of the triangle
                triplets = triplets + 1

    return triplets

我得到了错误:

    for item in L:
                 ^
SyntaxError: invalid syntax

为了完整起见,我的整个程序如下所示:

import math

def primes(n): #get a list of primes below a number
    if n==2: return [2]
    elif n<2: return []
    s=range(3,n+1,2)
    mroot = n ** 0.5
    half=(n+1)/2-1
    i=0
    m=3
    while m <= mroot:
        if s[i]:
            j=(m*m-3)/2
            s[j]=0
            while j<half:
                s[j]=0
                j+=m
        i=i+1
        m=2*i+3
    return [2]+[x for x in s if x]

def triplets(perimeter):

    triplets, n, a, b, c = 0  #number of triplets, a, b, c, sides of a triangle, n is used to calculate a triple
    L = primes(int(math.sqrt(perimeter)) #list of primes to divide the perimeter

    for item in L: #iterate through the list of primes
        if perimeter % item == 0: #check if a prime divides the perimeter
            n = perimeter / item
            a = n**2 - (n+1)**2 #http://en.wikipedia.org/wiki/Pythagorean_triple
            b = 2n*(n+1)
            c = n**2 + n**2
            if a+b+c == perimeter: #check if it adds up to the perimeter of the triangle
                triplets = triplets + 1

    return triplets

def solve():
    best = 0
    perimeter = 0
    for i in range(1, 1000):
        if triplets(i) > best:
            best = triplets(i)
            perimeter = i
    return perimeter

print solve()

我正在使用Python2.7.1。我在for循环后面有一个分号,primes(n)函数可以工作,我有一种感觉,这可能是愚蠢的事情,但我不知道是什么导致了这种无效语法。


Tags: ofthetoinforreturnifdef
3条回答

前面的行有错误:

L = primes(int(math.sqrt(perimeter))

你有三个开放式帕伦斯,但只有两个封闭式帕伦斯。

您在以下行之前缺少右括号:

      L = primes(int(math.sqrt(perimeter)) #list of primes to divide the perimeter
#                ^   ^         ^         ^^
#nesting count   1   2         3         21

看我们怎么在下面的“嵌套计数”中没有达到0?

缺少括号:

L = primes(int(math.sqrt(perimeter)))
                                    ^
                                    |
                                 this one

我经常遇到这种情况,你只需要看看之前的台词。

相关问题 更多 >