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.
Not too helpful.
Try this.
Helpful? Maybe.
Try this:
Hmmm. The
for i in aloop stops working, also. This generator object seems to do it’s thing once only. Either in a for loop or in thelist()(ortuple()) function but not both.Try this.
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
forstatement or thelist()function.Also, we’ve learned to add print statements to explore confusing syntax.