Skip to main content
Became Hot Network Question
Tweeted twitter.com/StackCodeReview/status/1161880303104856064
tags
Link
dfhwze
  • 14.2k
  • 3
  • 40
  • 101
Source Link

Sum Square Difference, which way is more Pythonic?

I'm using python 3 and I am creating an algorithm to find the sum square difference for the first 100 (or 1 to x) natural numbers. This happens to be project euler problem 6 if anyone is wondering.

I've written it two ways and I am looking for criticism on my writing style to further guide me in how I code algorithms. I am aware there is probably a better "optimized" solution in terms of big(o) but my math skills just haven't reached there yet.

Algorithm 1

def sum_square_difference(max_range):
    #Finds the sum square difference for the first x(max range) natural numbers
    numbers = range(1,max_range+1)
    sum_squares = sum([x**2 for x in numbers])
    square_sum = sum(numbers) ** 2
    return square_sum - sum_squares

I find this algorithm to be the most readable, but something tells me it may be more verbose in terms of lines of code than necessary so I wrote the following algorithm.

Algorithm 2

def sum_square_difference2(max_range):
    numbers = range(1,max_range+1)
    return (sum(numbers) ** 2) - (sum([x**2 for x in numbers]))

This one seems much cleaner, but I find myself struggling more to understand and read what is going on, especially when considering the perspective of an outside observer.

I appreciate any insight.