patternpythonMinor
Project Euler Problem 6: sum of squares and square of sums
Viewed 0 times
problemsquaresquaresprojecteulersumandsums
Problem
This is a very simple task, but I'm curious if there is a better, more 'Pythonic' way to solve this.
"""The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 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."""
square = 0
s = 0
for i in range(1, 101):
square += i**2
s += i
s = s**2
print(s - square)Solution
This would be good practice for list comprehension, especially since
For even more fanciness, you can use this expression for the sum_of_squares:
This sums over a generator expression instead of creating a new list, saving memory, especially if the sequence is something ridiculous like
sum() is a builtin function.sequence = range(1, 11)
sum_of_squares = sum([i**2 for i in sequence])
square_of_sum = sum(sequence)**2
print(square_of_sum - sum_of_squares) # 2640For even more fanciness, you can use this expression for the sum_of_squares:
sum_of_squares = sum(i**2 for i in sequence) # No square bracketsThis sums over a generator expression instead of creating a new list, saving memory, especially if the sequence is something ridiculous like
range(1, 1000000001).Code Snippets
sequence = range(1, 11)
sum_of_squares = sum([i**2 for i in sequence])
square_of_sum = sum(sequence)**2
print(square_of_sum - sum_of_squares) # 2640sum_of_squares = sum(i**2 for i in sequence) # No square bracketsContext
StackExchange Code Review Q#149936, answer score: 5
Revisions (0)
No revisions yet.