2012-01-16 177 views
7

我有一種感覺,我在這裏的東西很簡單,但在這一個功能:無效語法

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)函數起作用,我有一種感覺可能是愚蠢的,但我無法弄清楚它是什麼導致這個無效的語法。

+0

「L = ...'行中的括號 – 2017-06-07 20:09:06

回答

13

你缺少前上線一個右括號:

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

看看我們如何不與線下達成的「嵌套數」 0?

+0

拍攝。我知道這很簡單。很尷尬。哈哈。謝謝。 – Dair 2012-01-16 21:50:55

+0

只是想評論一下:我犯了另外兩個錯誤(我後來發現):'b = 2n *(n + 1)'也應該是'b = 2 * n *(n + 1)',我需要以不同方式初始化三元組a,b,c和n。 – Dair 2012-01-16 21:56:26

0

沒有在該行的錯誤之前:

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

你有3個開括號,但只有兩個收盤括號。

0

的錯誤是在線以上 - 你缺少一個右括號:

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

你缺少一個括號:

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

這發生在我身上所有的時候,你只需要看看之前的行。