Invalid syntax in loop "for item in L"

I have the feeling that I missed something rather simple, but in this one function:

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 

I get an error message:

  for item in L: ^ SyntaxError: invalid syntax 

For completeness, my entire program looks like this:

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

I am using Python 2.7.1. I have a semicolon after the for loop, the primes(n) function works, I have a feeling that this is probably something stupid, but I can’t understand what exactly this invalid syntax is causing.

+7
source share
4 answers

You are missing the closing parenthesis in the line:

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

See how we did not reach 0 in the "nesting count" below the line?

+13
source

You are missing a parenthesis:

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

This happens to me all the time, you just need to look at the line earlier.

+1
source

There is an error in the line:

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

You have 3 open parens, but only two closing parens.

0
source

The error in the line above is that you are missing a parenthesis:

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

All Articles