无效语法
问题描述:
我有一种感觉,我在这里的东西很简单,但在这一个功能:无效语法
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)
函数起作用,我有一种感觉可能是愚蠢的,但我无法弄清楚它是什么导致这个无效的语法。
答
你缺少前上线一个右括号:
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))
你有3个开括号,但只有两个收盘括号。
答
的错误是在线以上 - 你缺少一个右括号:
L = primes(int(math.sqrt(perimeter)))
答
你缺少一个括号:
L = primes(int(math.sqrt(perimeter)))
^
|
this one
这发生在我身上所有的时候,你只需要看看之前的行。
“L = ...'行中的括号 – 2017-06-07 20:09:06