for item in L" 循环中的语法错误

9 投票
4 回答
58684 浏览
提问于 2025-04-17 10:23

我感觉我在这里漏掉了一些很简单的东西,但在这个函数里:

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()

我使用的是Python 2.7.1。在for循环后面有一个分号,primes(n)这个函数是可以正常工作的,我觉得可能是一些很简单的错误,但我就是搞不清楚是什么导致了这个无效的语法。

4 个回答

0

在它之前的那行代码有个错误:

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

你有三个左括号,但只有两个右括号。

1

你少了一个括号:

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

我经常遇到这种情况,你只需要看看前面的那一行就行了。

18

你在前面的一行代码中缺少一个右括号:

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

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

撰写回答