"The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 − 385 = 2640.Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum."
To do a square in Python, two * is used: "**". This time I'm going to be a little more detailed about how I produce the correct answer. First I reproduce the example given:
sumOfSquares = 0sumToSquare = 0squareOfSum = 0difference = 0 for x in range(1,11): sumOfSquares += x ** 2 print(sumOfSquares) for y in range(1,11): sumToSquare += y print(sumToSquare) squareOfSum = sumToSquare ** 2print(squareOfSum) difference = squareOfSum - sumOfSquares print(difference)
Not a very nice code, but it works. Then I change the upper limits in the two for-loops to 101 instead of 11 and put it into the website to verify that I've got it right.
Then I try to make the code look better. This I do because I think it's a good way to learn. Maybe I can do it all in just one for-loop? Let's try. As I've read somewhere, it seems that it's good programming practise to make the code easy to read instead of just doing it on as few lines as possible, so here we go with a more compact, and probably more effective, version:
sumOfSquares = 0sumToSquare = 0squareOfSum = 0difference = 0 for x in range(1,101): sumOfSquares += x ** 2 sumToSquare += x squareOfSum = sumToSquare ** 2difference = squareOfSum - sumOfSquares print(difference)
/Ludvig
No comments:
Post a Comment