2012-01-16 13 views
7

私はここに非常に単純な何かが欠けていたが、この1つの関数に気持ちがあります。無効な構文

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 = ...'行の括弧 –

答えて

13

あなたは前の行に閉じ括弧が欠落している:私たちは線の下の「ネスト数」に0に到達しない方法を参照してください

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

+0

シュート。私はそれが何か簡単だと分かっていました。とても恥ずかしい。ハハ。ありがとう。 – Dair

+0

ちょうどコメントしたいと思います:私は後で見つけた2つの間違いをしました: 'b = 2n *(n + 1)'は 'b = 2 * n *(n + 1)'でなければなりません。三つ組a、b、c、nを別々に初期化する。 – Dair

0

その前の行にエラーがあります:

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

あなたは3つの開いた括弧、2つだけ閉じる括弧があります。あなたは、これは私にすべての回起こる

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

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

エラーが上記の行にあります前の行を見てみるだけです。

1

あなたは括弧が欠落している:あなたは閉じ括弧が欠落している -