开发者

Explanation of syntax in for loop?

I was trying to do some of the problems on projecteuler, and I got to the one with the sum of squares and squares of sums. I didn't want to brute force it, so I looked up the solution, which was:

开发者_开发技巧
sum1 = 0
sum2 = 0

for i in ((x,x ** 2) for x in range(1,100+1)):
    sum1 += i[0]
    sum2 += i[-1]

print(sum1 ** 2 - sum2)

I do not get:

(x,x ** 2) for x in range(1,100+1)

I've seen this in another code golf solution in javascript too. Is this a specific syntax, or an unfamiliar way of something regular? Can someone please explain?


When confronted with complex syntax, add print statements.

for i in ((x,x ** 2) for x in range(1,100+1)):
    print i

Not too helpful.

Try this.

a = ((x,x ** 2) for x in range(1,100+1))
print a
for i in a:
     print i

Helpful? Maybe.

Try this:

a = ((x,x ** 2) for x in range(1,100+1))
b = list(a)
print b

Hmmm. The for i in a loop stops working, also. This generator object seems to do it's thing once only. Either in a for loop or in the list() (or tuple()) function but not both.

Try this.

 for x in range(1,100+1): 
      print x, x**2

Okay. So, what have we learned?

((x,x ** 2) for x in range(1,100+1)) is a generator expression. http://www.python.org/dev/peps/pep-0289/

It's "iterable" and can be used in a for statement or the list() function.

Also, we've learned to add print statements to explore confusing syntax.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜