Sum Square Difference, which way is more Pythonic?Maintaining the Single Responsibility Principle with Project Euler #2Sum of Squares/Square of Sum DifferenceSum of numbers which are not sum of two abundant numbersProject Euler Problem #6 - sum square differenceProject Euler #6 in JavaProject Euler 6: Difference between sum of squares and square of sumProject Euler #6 - Sum square differenceFind good numbers in a given rangeProject Euler Problem 6: Sum square differencePython sum of multiples of some numbers in a range

Count the number of shortest paths to n

How do we improve collaboration with problematic tester team?

What is the name of this plot that has rows with two connected dots?

Why didn't Doc believe Marty was from the future?

Is this password scheme legit?

What are the IPSE’s, the ASPE’s, the FRIPSE’s and the GRIPSE’s?

Many many thanks

Defending Castle from Zombies

Can I get a PhD for developing an educational software?

What is the 3D printer filament (or pellet) most resistant to bending at high heats?

What to do about my 1-month-old boy peeing through diapers?

Is a Centaur PC considered an animal when calculating carrying capacity for vehicles?

How to pass 2>/dev/null as a variable?

Can someone identify this unusual plane at airport?

Why is sh (not bash) complaining about functions defined in my .bashrc?

rationalizing sieges in a modern/near-future setting

Notice period 60 days but I need to join in 45 days

Book featuring a child learning from a crowdsourced AI book

Counting the triangles that can be formed from segments of given lengths

Should an STL container avoid copying elements into themselves when the container is copied into itself?

Finding square root without division and initial guess

Why did James Cameron decide to give Alita big eyes?

Why is getting a PhD considered "financially irresponsible" by some people?

How to force GCC to assume that a floating-point expression is non-negative?



Sum Square Difference, which way is more Pythonic?


Maintaining the Single Responsibility Principle with Project Euler #2Sum of Squares/Square of Sum DifferenceSum of numbers which are not sum of two abundant numbersProject Euler Problem #6 - sum square differenceProject Euler #6 in JavaProject Euler 6: Difference between sum of squares and square of sumProject Euler #6 - Sum square differenceFind good numbers in a given rangeProject Euler Problem 6: Sum square differencePython sum of multiples of some numbers in a range






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








10












$begingroup$


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.










share|improve this question











$endgroup$









  • 1




    $begingroup$
    Why not just utilize the identities for the sum of the first N squares and the one for the first N integers? i.e. n * (n + 1) * (2*n + 1) / 6 - n**2 * (n + 1)**2 / 4. But of course, as suggested in the answers, comment your method... You could probably even simplify that some algebraically...
    $endgroup$
    – twalberg
    Aug 16 at 18:27


















10












$begingroup$


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.










share|improve this question











$endgroup$









  • 1




    $begingroup$
    Why not just utilize the identities for the sum of the first N squares and the one for the first N integers? i.e. n * (n + 1) * (2*n + 1) / 6 - n**2 * (n + 1)**2 / 4. But of course, as suggested in the answers, comment your method... You could probably even simplify that some algebraically...
    $endgroup$
    – twalberg
    Aug 16 at 18:27














10












10








10


1



$begingroup$


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.










share|improve this question











$endgroup$




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.







python python-3.x programming-challenge comparative-review






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 14 at 21:58









dfhwze

9,7872 gold badges19 silver badges63 bronze badges




9,7872 gold badges19 silver badges63 bronze badges










asked Aug 14 at 21:53









takethelongsh0ttakethelongsh0t

561 silver badge6 bronze badges




561 silver badge6 bronze badges










  • 1




    $begingroup$
    Why not just utilize the identities for the sum of the first N squares and the one for the first N integers? i.e. n * (n + 1) * (2*n + 1) / 6 - n**2 * (n + 1)**2 / 4. But of course, as suggested in the answers, comment your method... You could probably even simplify that some algebraically...
    $endgroup$
    – twalberg
    Aug 16 at 18:27













  • 1




    $begingroup$
    Why not just utilize the identities for the sum of the first N squares and the one for the first N integers? i.e. n * (n + 1) * (2*n + 1) / 6 - n**2 * (n + 1)**2 / 4. But of course, as suggested in the answers, comment your method... You could probably even simplify that some algebraically...
    $endgroup$
    – twalberg
    Aug 16 at 18:27








1




1




$begingroup$
Why not just utilize the identities for the sum of the first N squares and the one for the first N integers? i.e. n * (n + 1) * (2*n + 1) / 6 - n**2 * (n + 1)**2 / 4. But of course, as suggested in the answers, comment your method... You could probably even simplify that some algebraically...
$endgroup$
– twalberg
Aug 16 at 18:27





$begingroup$
Why not just utilize the identities for the sum of the first N squares and the one for the first N integers? i.e. n * (n + 1) * (2*n + 1) / 6 - n**2 * (n + 1)**2 / 4. But of course, as suggested in the answers, comment your method... You could probably even simplify that some algebraically...
$endgroup$
– twalberg
Aug 16 at 18:27











4 Answers
4






active

oldest

votes


















18













$begingroup$

I would do something like:



def sum_of_squares(n):
return sum(i ** 2 for i in range(1, n+1))

def square_of_sum(n):
return sum(range(1, n+1)) ** 2

def sum_square_difference(n):
return sum_of_squares(n) - square_of_sum(n)


Notice the use of a generator expression in sum, where I have omitted the square brackets.






share|improve this answer









$endgroup$










  • 7




    $begingroup$
    I find that people often recommend splitting up already small functions into even smaller functions, but personally I find that this can take longer when debugging, as you can't tell at a glance if the function is used in more than one place.
    $endgroup$
    – Turksarama
    Aug 15 at 6:15










  • $begingroup$
    @Turksarama With a decent editor (that supports highlighting), certainly you can.
    $endgroup$
    – Kenneth K.
    Aug 15 at 14:10










  • $begingroup$
    Even without a decent editor (I use Atom), a folder-wide search works just fine. Ctrl+Shift+F, "square_of_sum(". Doesn't work for aliasing, but oh well, tests should catch that.
    $endgroup$
    – Adam Barnes
    Aug 16 at 12:50



















15













$begingroup$


I find myself struggling more to understand and read what is going on




This is the key insight. A chunk of code is likely to be read more times than it was written. So write your code to be read. Use comments, docstrings, whitespace, type hints, etc. to make it easier for someone unfamiliar with the code (including your future self) to read and understand it.






share|improve this answer









$endgroup$






















    9













    $begingroup$

    An alternative not discussed in the other answers: use numpy. As soon as you want to do anything serious with numbers, it's going to be useful. The downside is that numpy uses fixed-size integers, which can lead to overflow. It also allocates the array, which uses more memory than necessary.



    import numpy as np

    def sum_square_difference(n):
    nums = np.arange(1, n+1, dtype=int)
    return nums.sum()**2 - (nums**2).sum()


    If you want to input very large numbers, or have access to very little memory, just use the analytical formulas for the sums:



    def sum_square_analytical(n):
    sum_squares = n*(n+1)*(2*n+1)//6
    square_sum = (n*(n+1)//2)**2
    return square_sum - sum_squares


    Of course, you can add docstrings and comments, as suggested in other answers.






    share|improve this answer









    $endgroup$










    • 2




      $begingroup$
      If you're going to do the math, you might as well do the subtraction as well, no? Then sum_square_analytical is just return (3*n**4 + 2*n**3 - 3*n**2 - 2*n)//12. Or factor it, which seems faster: return n*(n+1)*(n-1)*(3*n+2)//12
      $endgroup$
      – Nick Matteo
      Aug 16 at 6:51











    • $begingroup$
      @NickMatteo Of course you could simplify it even further, I just wanted to present the way I would have done it. I prefer splitting up the logic, since generally you could have more complicated formulas, and combining them adds an extra layer of debugging for a future developer. I just googled the closed expressions for these sums, and wrote them into the code. That way, it will be easy for any future developer to verify that these formulas are correct.
      $endgroup$
      – maxb
      Aug 16 at 7:36










    • $begingroup$
      I -1'd this (even though I don't have the reputation to), because I would argue this is not answering the OP's question. He's not asking for the best computational way to do the sum of squares, he's asking for the most readable. numpy is very much unreadable to the initiated. Compare your examples to Nikos Oikou's, from the perspective of someone who knows Python, but has never used numpy.
      $endgroup$
      – Adam Barnes
      Aug 16 at 12:52










    • $begingroup$
      @AdamBarnes It is entirely possible to learn Python without ever touching numpy, but I'd definitely argue that the example I provided is in no way unreadable. Even to someone who has barely touched Python, I'd argue that (nums**2).sum() is more readable than sum(n**2 for n in nums). However, I might be biased from having used numpy extensively. I definitely find Nikos Oikou's answer clear, concise and readable, but I wanted to present alternative approaches that might be usable. And in my own opinion, anyone learning Python should also put some focus on numpy.
      $endgroup$
      – maxb
      Aug 16 at 13:04


















    4













    $begingroup$

    Docstrings:



    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


    When you define a function and include a docstring, it should be contained within triple quotes instead of # that is used for comments.



    Like this:



    def sum_square_difference(max_range):
    """ Explanation goes here """


    Regarding the syntax or how you write the code, you might do it in one line instead of the use of many unnecessary variables.



    Like this:



    def square_difference(upper_bound):
    """Return sum numbers squared - sum of squares in range upper_bound inclusive."""
    return sum(range(1, upper_bound + 1)) ** 2 - sum(x ** 2 for x in range(1, upper_bound + 1))


    You might want to check pep8 https://www.python.org/dev/peps/pep-0008/ - the official Python style guide.






    share|improve this answer









    $endgroup$










    • 3




      $begingroup$
      I don't think I agree with the idea of removing the definition of the range, it is much clearer that the same range is used twice if you assign it to a variable first.
      $endgroup$
      – Turksarama
      Aug 15 at 6:13










    • $begingroup$
      If you're referring to the style guide, you should also limit your maximum line length to 79 characters. You can still have it as one expression, split over multiple lines.
      $endgroup$
      – maxb
      Aug 15 at 7:24










    • $begingroup$
      unnecessary variables can you explain this point? I think that in general code with more usefully-named variables is easier to maintain than long lines of code like yours
      $endgroup$
      – user2023861
      Aug 15 at 16:13










    • $begingroup$
      @user2023861 a variable is unnecessary if we can use its value and directly compute a one time calculation, if the value will be used more than once, then a variable is necessary and from my understanding, the author of the post wanted to minimize the lines of code therefore, I omitted whatever variables I consider to be unnecessary and replaced them with one line comprehension syntax which is faster and shorter.
      $endgroup$
      – emadboctor
      Aug 15 at 16:22






    • 1




      $begingroup$
      @emadboctor OP says that algorithm2 isn't as good because he struggles to read and understand the code. Algorithm2 is the one with fewer variables. Variables with useful names document themselves, even if they're only used once. That's why it's probably better to have more variables.
      $endgroup$
      – user2023861
      Aug 15 at 18:18













    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f226138%2fsum-square-difference-which-way-is-more-pythonic%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    18













    $begingroup$

    I would do something like:



    def sum_of_squares(n):
    return sum(i ** 2 for i in range(1, n+1))

    def square_of_sum(n):
    return sum(range(1, n+1)) ** 2

    def sum_square_difference(n):
    return sum_of_squares(n) - square_of_sum(n)


    Notice the use of a generator expression in sum, where I have omitted the square brackets.






    share|improve this answer









    $endgroup$










    • 7




      $begingroup$
      I find that people often recommend splitting up already small functions into even smaller functions, but personally I find that this can take longer when debugging, as you can't tell at a glance if the function is used in more than one place.
      $endgroup$
      – Turksarama
      Aug 15 at 6:15










    • $begingroup$
      @Turksarama With a decent editor (that supports highlighting), certainly you can.
      $endgroup$
      – Kenneth K.
      Aug 15 at 14:10










    • $begingroup$
      Even without a decent editor (I use Atom), a folder-wide search works just fine. Ctrl+Shift+F, "square_of_sum(". Doesn't work for aliasing, but oh well, tests should catch that.
      $endgroup$
      – Adam Barnes
      Aug 16 at 12:50
















    18













    $begingroup$

    I would do something like:



    def sum_of_squares(n):
    return sum(i ** 2 for i in range(1, n+1))

    def square_of_sum(n):
    return sum(range(1, n+1)) ** 2

    def sum_square_difference(n):
    return sum_of_squares(n) - square_of_sum(n)


    Notice the use of a generator expression in sum, where I have omitted the square brackets.






    share|improve this answer









    $endgroup$










    • 7




      $begingroup$
      I find that people often recommend splitting up already small functions into even smaller functions, but personally I find that this can take longer when debugging, as you can't tell at a glance if the function is used in more than one place.
      $endgroup$
      – Turksarama
      Aug 15 at 6:15










    • $begingroup$
      @Turksarama With a decent editor (that supports highlighting), certainly you can.
      $endgroup$
      – Kenneth K.
      Aug 15 at 14:10










    • $begingroup$
      Even without a decent editor (I use Atom), a folder-wide search works just fine. Ctrl+Shift+F, "square_of_sum(". Doesn't work for aliasing, but oh well, tests should catch that.
      $endgroup$
      – Adam Barnes
      Aug 16 at 12:50














    18














    18










    18







    $begingroup$

    I would do something like:



    def sum_of_squares(n):
    return sum(i ** 2 for i in range(1, n+1))

    def square_of_sum(n):
    return sum(range(1, n+1)) ** 2

    def sum_square_difference(n):
    return sum_of_squares(n) - square_of_sum(n)


    Notice the use of a generator expression in sum, where I have omitted the square brackets.






    share|improve this answer









    $endgroup$



    I would do something like:



    def sum_of_squares(n):
    return sum(i ** 2 for i in range(1, n+1))

    def square_of_sum(n):
    return sum(range(1, n+1)) ** 2

    def sum_square_difference(n):
    return sum_of_squares(n) - square_of_sum(n)


    Notice the use of a generator expression in sum, where I have omitted the square brackets.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Aug 14 at 22:29









    Nikos OikouNikos Oikou

    3614 bronze badges




    3614 bronze badges










    • 7




      $begingroup$
      I find that people often recommend splitting up already small functions into even smaller functions, but personally I find that this can take longer when debugging, as you can't tell at a glance if the function is used in more than one place.
      $endgroup$
      – Turksarama
      Aug 15 at 6:15










    • $begingroup$
      @Turksarama With a decent editor (that supports highlighting), certainly you can.
      $endgroup$
      – Kenneth K.
      Aug 15 at 14:10










    • $begingroup$
      Even without a decent editor (I use Atom), a folder-wide search works just fine. Ctrl+Shift+F, "square_of_sum(". Doesn't work for aliasing, but oh well, tests should catch that.
      $endgroup$
      – Adam Barnes
      Aug 16 at 12:50













    • 7




      $begingroup$
      I find that people often recommend splitting up already small functions into even smaller functions, but personally I find that this can take longer when debugging, as you can't tell at a glance if the function is used in more than one place.
      $endgroup$
      – Turksarama
      Aug 15 at 6:15










    • $begingroup$
      @Turksarama With a decent editor (that supports highlighting), certainly you can.
      $endgroup$
      – Kenneth K.
      Aug 15 at 14:10










    • $begingroup$
      Even without a decent editor (I use Atom), a folder-wide search works just fine. Ctrl+Shift+F, "square_of_sum(". Doesn't work for aliasing, but oh well, tests should catch that.
      $endgroup$
      – Adam Barnes
      Aug 16 at 12:50








    7




    7




    $begingroup$
    I find that people often recommend splitting up already small functions into even smaller functions, but personally I find that this can take longer when debugging, as you can't tell at a glance if the function is used in more than one place.
    $endgroup$
    – Turksarama
    Aug 15 at 6:15




    $begingroup$
    I find that people often recommend splitting up already small functions into even smaller functions, but personally I find that this can take longer when debugging, as you can't tell at a glance if the function is used in more than one place.
    $endgroup$
    – Turksarama
    Aug 15 at 6:15












    $begingroup$
    @Turksarama With a decent editor (that supports highlighting), certainly you can.
    $endgroup$
    – Kenneth K.
    Aug 15 at 14:10




    $begingroup$
    @Turksarama With a decent editor (that supports highlighting), certainly you can.
    $endgroup$
    – Kenneth K.
    Aug 15 at 14:10












    $begingroup$
    Even without a decent editor (I use Atom), a folder-wide search works just fine. Ctrl+Shift+F, "square_of_sum(". Doesn't work for aliasing, but oh well, tests should catch that.
    $endgroup$
    – Adam Barnes
    Aug 16 at 12:50





    $begingroup$
    Even without a decent editor (I use Atom), a folder-wide search works just fine. Ctrl+Shift+F, "square_of_sum(". Doesn't work for aliasing, but oh well, tests should catch that.
    $endgroup$
    – Adam Barnes
    Aug 16 at 12:50














    15













    $begingroup$


    I find myself struggling more to understand and read what is going on




    This is the key insight. A chunk of code is likely to be read more times than it was written. So write your code to be read. Use comments, docstrings, whitespace, type hints, etc. to make it easier for someone unfamiliar with the code (including your future self) to read and understand it.






    share|improve this answer









    $endgroup$



















      15













      $begingroup$


      I find myself struggling more to understand and read what is going on




      This is the key insight. A chunk of code is likely to be read more times than it was written. So write your code to be read. Use comments, docstrings, whitespace, type hints, etc. to make it easier for someone unfamiliar with the code (including your future self) to read and understand it.






      share|improve this answer









      $endgroup$

















        15














        15










        15







        $begingroup$


        I find myself struggling more to understand and read what is going on




        This is the key insight. A chunk of code is likely to be read more times than it was written. So write your code to be read. Use comments, docstrings, whitespace, type hints, etc. to make it easier for someone unfamiliar with the code (including your future self) to read and understand it.






        share|improve this answer









        $endgroup$




        I find myself struggling more to understand and read what is going on




        This is the key insight. A chunk of code is likely to be read more times than it was written. So write your code to be read. Use comments, docstrings, whitespace, type hints, etc. to make it easier for someone unfamiliar with the code (including your future self) to read and understand it.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Aug 14 at 23:02









        RootTwoRootTwo

        1,5943 silver badges9 bronze badges




        1,5943 silver badges9 bronze badges
























            9













            $begingroup$

            An alternative not discussed in the other answers: use numpy. As soon as you want to do anything serious with numbers, it's going to be useful. The downside is that numpy uses fixed-size integers, which can lead to overflow. It also allocates the array, which uses more memory than necessary.



            import numpy as np

            def sum_square_difference(n):
            nums = np.arange(1, n+1, dtype=int)
            return nums.sum()**2 - (nums**2).sum()


            If you want to input very large numbers, or have access to very little memory, just use the analytical formulas for the sums:



            def sum_square_analytical(n):
            sum_squares = n*(n+1)*(2*n+1)//6
            square_sum = (n*(n+1)//2)**2
            return square_sum - sum_squares


            Of course, you can add docstrings and comments, as suggested in other answers.






            share|improve this answer









            $endgroup$










            • 2




              $begingroup$
              If you're going to do the math, you might as well do the subtraction as well, no? Then sum_square_analytical is just return (3*n**4 + 2*n**3 - 3*n**2 - 2*n)//12. Or factor it, which seems faster: return n*(n+1)*(n-1)*(3*n+2)//12
              $endgroup$
              – Nick Matteo
              Aug 16 at 6:51











            • $begingroup$
              @NickMatteo Of course you could simplify it even further, I just wanted to present the way I would have done it. I prefer splitting up the logic, since generally you could have more complicated formulas, and combining them adds an extra layer of debugging for a future developer. I just googled the closed expressions for these sums, and wrote them into the code. That way, it will be easy for any future developer to verify that these formulas are correct.
              $endgroup$
              – maxb
              Aug 16 at 7:36










            • $begingroup$
              I -1'd this (even though I don't have the reputation to), because I would argue this is not answering the OP's question. He's not asking for the best computational way to do the sum of squares, he's asking for the most readable. numpy is very much unreadable to the initiated. Compare your examples to Nikos Oikou's, from the perspective of someone who knows Python, but has never used numpy.
              $endgroup$
              – Adam Barnes
              Aug 16 at 12:52










            • $begingroup$
              @AdamBarnes It is entirely possible to learn Python without ever touching numpy, but I'd definitely argue that the example I provided is in no way unreadable. Even to someone who has barely touched Python, I'd argue that (nums**2).sum() is more readable than sum(n**2 for n in nums). However, I might be biased from having used numpy extensively. I definitely find Nikos Oikou's answer clear, concise and readable, but I wanted to present alternative approaches that might be usable. And in my own opinion, anyone learning Python should also put some focus on numpy.
              $endgroup$
              – maxb
              Aug 16 at 13:04















            9













            $begingroup$

            An alternative not discussed in the other answers: use numpy. As soon as you want to do anything serious with numbers, it's going to be useful. The downside is that numpy uses fixed-size integers, which can lead to overflow. It also allocates the array, which uses more memory than necessary.



            import numpy as np

            def sum_square_difference(n):
            nums = np.arange(1, n+1, dtype=int)
            return nums.sum()**2 - (nums**2).sum()


            If you want to input very large numbers, or have access to very little memory, just use the analytical formulas for the sums:



            def sum_square_analytical(n):
            sum_squares = n*(n+1)*(2*n+1)//6
            square_sum = (n*(n+1)//2)**2
            return square_sum - sum_squares


            Of course, you can add docstrings and comments, as suggested in other answers.






            share|improve this answer









            $endgroup$










            • 2




              $begingroup$
              If you're going to do the math, you might as well do the subtraction as well, no? Then sum_square_analytical is just return (3*n**4 + 2*n**3 - 3*n**2 - 2*n)//12. Or factor it, which seems faster: return n*(n+1)*(n-1)*(3*n+2)//12
              $endgroup$
              – Nick Matteo
              Aug 16 at 6:51











            • $begingroup$
              @NickMatteo Of course you could simplify it even further, I just wanted to present the way I would have done it. I prefer splitting up the logic, since generally you could have more complicated formulas, and combining them adds an extra layer of debugging for a future developer. I just googled the closed expressions for these sums, and wrote them into the code. That way, it will be easy for any future developer to verify that these formulas are correct.
              $endgroup$
              – maxb
              Aug 16 at 7:36










            • $begingroup$
              I -1'd this (even though I don't have the reputation to), because I would argue this is not answering the OP's question. He's not asking for the best computational way to do the sum of squares, he's asking for the most readable. numpy is very much unreadable to the initiated. Compare your examples to Nikos Oikou's, from the perspective of someone who knows Python, but has never used numpy.
              $endgroup$
              – Adam Barnes
              Aug 16 at 12:52










            • $begingroup$
              @AdamBarnes It is entirely possible to learn Python without ever touching numpy, but I'd definitely argue that the example I provided is in no way unreadable. Even to someone who has barely touched Python, I'd argue that (nums**2).sum() is more readable than sum(n**2 for n in nums). However, I might be biased from having used numpy extensively. I definitely find Nikos Oikou's answer clear, concise and readable, but I wanted to present alternative approaches that might be usable. And in my own opinion, anyone learning Python should also put some focus on numpy.
              $endgroup$
              – maxb
              Aug 16 at 13:04













            9














            9










            9







            $begingroup$

            An alternative not discussed in the other answers: use numpy. As soon as you want to do anything serious with numbers, it's going to be useful. The downside is that numpy uses fixed-size integers, which can lead to overflow. It also allocates the array, which uses more memory than necessary.



            import numpy as np

            def sum_square_difference(n):
            nums = np.arange(1, n+1, dtype=int)
            return nums.sum()**2 - (nums**2).sum()


            If you want to input very large numbers, or have access to very little memory, just use the analytical formulas for the sums:



            def sum_square_analytical(n):
            sum_squares = n*(n+1)*(2*n+1)//6
            square_sum = (n*(n+1)//2)**2
            return square_sum - sum_squares


            Of course, you can add docstrings and comments, as suggested in other answers.






            share|improve this answer









            $endgroup$



            An alternative not discussed in the other answers: use numpy. As soon as you want to do anything serious with numbers, it's going to be useful. The downside is that numpy uses fixed-size integers, which can lead to overflow. It also allocates the array, which uses more memory than necessary.



            import numpy as np

            def sum_square_difference(n):
            nums = np.arange(1, n+1, dtype=int)
            return nums.sum()**2 - (nums**2).sum()


            If you want to input very large numbers, or have access to very little memory, just use the analytical formulas for the sums:



            def sum_square_analytical(n):
            sum_squares = n*(n+1)*(2*n+1)//6
            square_sum = (n*(n+1)//2)**2
            return square_sum - sum_squares


            Of course, you can add docstrings and comments, as suggested in other answers.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 15 at 7:51









            maxbmaxb

            1,3224 silver badges16 bronze badges




            1,3224 silver badges16 bronze badges










            • 2




              $begingroup$
              If you're going to do the math, you might as well do the subtraction as well, no? Then sum_square_analytical is just return (3*n**4 + 2*n**3 - 3*n**2 - 2*n)//12. Or factor it, which seems faster: return n*(n+1)*(n-1)*(3*n+2)//12
              $endgroup$
              – Nick Matteo
              Aug 16 at 6:51











            • $begingroup$
              @NickMatteo Of course you could simplify it even further, I just wanted to present the way I would have done it. I prefer splitting up the logic, since generally you could have more complicated formulas, and combining them adds an extra layer of debugging for a future developer. I just googled the closed expressions for these sums, and wrote them into the code. That way, it will be easy for any future developer to verify that these formulas are correct.
              $endgroup$
              – maxb
              Aug 16 at 7:36










            • $begingroup$
              I -1'd this (even though I don't have the reputation to), because I would argue this is not answering the OP's question. He's not asking for the best computational way to do the sum of squares, he's asking for the most readable. numpy is very much unreadable to the initiated. Compare your examples to Nikos Oikou's, from the perspective of someone who knows Python, but has never used numpy.
              $endgroup$
              – Adam Barnes
              Aug 16 at 12:52










            • $begingroup$
              @AdamBarnes It is entirely possible to learn Python without ever touching numpy, but I'd definitely argue that the example I provided is in no way unreadable. Even to someone who has barely touched Python, I'd argue that (nums**2).sum() is more readable than sum(n**2 for n in nums). However, I might be biased from having used numpy extensively. I definitely find Nikos Oikou's answer clear, concise and readable, but I wanted to present alternative approaches that might be usable. And in my own opinion, anyone learning Python should also put some focus on numpy.
              $endgroup$
              – maxb
              Aug 16 at 13:04












            • 2




              $begingroup$
              If you're going to do the math, you might as well do the subtraction as well, no? Then sum_square_analytical is just return (3*n**4 + 2*n**3 - 3*n**2 - 2*n)//12. Or factor it, which seems faster: return n*(n+1)*(n-1)*(3*n+2)//12
              $endgroup$
              – Nick Matteo
              Aug 16 at 6:51











            • $begingroup$
              @NickMatteo Of course you could simplify it even further, I just wanted to present the way I would have done it. I prefer splitting up the logic, since generally you could have more complicated formulas, and combining them adds an extra layer of debugging for a future developer. I just googled the closed expressions for these sums, and wrote them into the code. That way, it will be easy for any future developer to verify that these formulas are correct.
              $endgroup$
              – maxb
              Aug 16 at 7:36










            • $begingroup$
              I -1'd this (even though I don't have the reputation to), because I would argue this is not answering the OP's question. He's not asking for the best computational way to do the sum of squares, he's asking for the most readable. numpy is very much unreadable to the initiated. Compare your examples to Nikos Oikou's, from the perspective of someone who knows Python, but has never used numpy.
              $endgroup$
              – Adam Barnes
              Aug 16 at 12:52










            • $begingroup$
              @AdamBarnes It is entirely possible to learn Python without ever touching numpy, but I'd definitely argue that the example I provided is in no way unreadable. Even to someone who has barely touched Python, I'd argue that (nums**2).sum() is more readable than sum(n**2 for n in nums). However, I might be biased from having used numpy extensively. I definitely find Nikos Oikou's answer clear, concise and readable, but I wanted to present alternative approaches that might be usable. And in my own opinion, anyone learning Python should also put some focus on numpy.
              $endgroup$
              – maxb
              Aug 16 at 13:04







            2




            2




            $begingroup$
            If you're going to do the math, you might as well do the subtraction as well, no? Then sum_square_analytical is just return (3*n**4 + 2*n**3 - 3*n**2 - 2*n)//12. Or factor it, which seems faster: return n*(n+1)*(n-1)*(3*n+2)//12
            $endgroup$
            – Nick Matteo
            Aug 16 at 6:51





            $begingroup$
            If you're going to do the math, you might as well do the subtraction as well, no? Then sum_square_analytical is just return (3*n**4 + 2*n**3 - 3*n**2 - 2*n)//12. Or factor it, which seems faster: return n*(n+1)*(n-1)*(3*n+2)//12
            $endgroup$
            – Nick Matteo
            Aug 16 at 6:51













            $begingroup$
            @NickMatteo Of course you could simplify it even further, I just wanted to present the way I would have done it. I prefer splitting up the logic, since generally you could have more complicated formulas, and combining them adds an extra layer of debugging for a future developer. I just googled the closed expressions for these sums, and wrote them into the code. That way, it will be easy for any future developer to verify that these formulas are correct.
            $endgroup$
            – maxb
            Aug 16 at 7:36




            $begingroup$
            @NickMatteo Of course you could simplify it even further, I just wanted to present the way I would have done it. I prefer splitting up the logic, since generally you could have more complicated formulas, and combining them adds an extra layer of debugging for a future developer. I just googled the closed expressions for these sums, and wrote them into the code. That way, it will be easy for any future developer to verify that these formulas are correct.
            $endgroup$
            – maxb
            Aug 16 at 7:36












            $begingroup$
            I -1'd this (even though I don't have the reputation to), because I would argue this is not answering the OP's question. He's not asking for the best computational way to do the sum of squares, he's asking for the most readable. numpy is very much unreadable to the initiated. Compare your examples to Nikos Oikou's, from the perspective of someone who knows Python, but has never used numpy.
            $endgroup$
            – Adam Barnes
            Aug 16 at 12:52




            $begingroup$
            I -1'd this (even though I don't have the reputation to), because I would argue this is not answering the OP's question. He's not asking for the best computational way to do the sum of squares, he's asking for the most readable. numpy is very much unreadable to the initiated. Compare your examples to Nikos Oikou's, from the perspective of someone who knows Python, but has never used numpy.
            $endgroup$
            – Adam Barnes
            Aug 16 at 12:52












            $begingroup$
            @AdamBarnes It is entirely possible to learn Python without ever touching numpy, but I'd definitely argue that the example I provided is in no way unreadable. Even to someone who has barely touched Python, I'd argue that (nums**2).sum() is more readable than sum(n**2 for n in nums). However, I might be biased from having used numpy extensively. I definitely find Nikos Oikou's answer clear, concise and readable, but I wanted to present alternative approaches that might be usable. And in my own opinion, anyone learning Python should also put some focus on numpy.
            $endgroup$
            – maxb
            Aug 16 at 13:04




            $begingroup$
            @AdamBarnes It is entirely possible to learn Python without ever touching numpy, but I'd definitely argue that the example I provided is in no way unreadable. Even to someone who has barely touched Python, I'd argue that (nums**2).sum() is more readable than sum(n**2 for n in nums). However, I might be biased from having used numpy extensively. I definitely find Nikos Oikou's answer clear, concise and readable, but I wanted to present alternative approaches that might be usable. And in my own opinion, anyone learning Python should also put some focus on numpy.
            $endgroup$
            – maxb
            Aug 16 at 13:04











            4













            $begingroup$

            Docstrings:



            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


            When you define a function and include a docstring, it should be contained within triple quotes instead of # that is used for comments.



            Like this:



            def sum_square_difference(max_range):
            """ Explanation goes here """


            Regarding the syntax or how you write the code, you might do it in one line instead of the use of many unnecessary variables.



            Like this:



            def square_difference(upper_bound):
            """Return sum numbers squared - sum of squares in range upper_bound inclusive."""
            return sum(range(1, upper_bound + 1)) ** 2 - sum(x ** 2 for x in range(1, upper_bound + 1))


            You might want to check pep8 https://www.python.org/dev/peps/pep-0008/ - the official Python style guide.






            share|improve this answer









            $endgroup$










            • 3




              $begingroup$
              I don't think I agree with the idea of removing the definition of the range, it is much clearer that the same range is used twice if you assign it to a variable first.
              $endgroup$
              – Turksarama
              Aug 15 at 6:13










            • $begingroup$
              If you're referring to the style guide, you should also limit your maximum line length to 79 characters. You can still have it as one expression, split over multiple lines.
              $endgroup$
              – maxb
              Aug 15 at 7:24










            • $begingroup$
              unnecessary variables can you explain this point? I think that in general code with more usefully-named variables is easier to maintain than long lines of code like yours
              $endgroup$
              – user2023861
              Aug 15 at 16:13










            • $begingroup$
              @user2023861 a variable is unnecessary if we can use its value and directly compute a one time calculation, if the value will be used more than once, then a variable is necessary and from my understanding, the author of the post wanted to minimize the lines of code therefore, I omitted whatever variables I consider to be unnecessary and replaced them with one line comprehension syntax which is faster and shorter.
              $endgroup$
              – emadboctor
              Aug 15 at 16:22






            • 1




              $begingroup$
              @emadboctor OP says that algorithm2 isn't as good because he struggles to read and understand the code. Algorithm2 is the one with fewer variables. Variables with useful names document themselves, even if they're only used once. That's why it's probably better to have more variables.
              $endgroup$
              – user2023861
              Aug 15 at 18:18















            4













            $begingroup$

            Docstrings:



            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


            When you define a function and include a docstring, it should be contained within triple quotes instead of # that is used for comments.



            Like this:



            def sum_square_difference(max_range):
            """ Explanation goes here """


            Regarding the syntax or how you write the code, you might do it in one line instead of the use of many unnecessary variables.



            Like this:



            def square_difference(upper_bound):
            """Return sum numbers squared - sum of squares in range upper_bound inclusive."""
            return sum(range(1, upper_bound + 1)) ** 2 - sum(x ** 2 for x in range(1, upper_bound + 1))


            You might want to check pep8 https://www.python.org/dev/peps/pep-0008/ - the official Python style guide.






            share|improve this answer









            $endgroup$










            • 3




              $begingroup$
              I don't think I agree with the idea of removing the definition of the range, it is much clearer that the same range is used twice if you assign it to a variable first.
              $endgroup$
              – Turksarama
              Aug 15 at 6:13










            • $begingroup$
              If you're referring to the style guide, you should also limit your maximum line length to 79 characters. You can still have it as one expression, split over multiple lines.
              $endgroup$
              – maxb
              Aug 15 at 7:24










            • $begingroup$
              unnecessary variables can you explain this point? I think that in general code with more usefully-named variables is easier to maintain than long lines of code like yours
              $endgroup$
              – user2023861
              Aug 15 at 16:13










            • $begingroup$
              @user2023861 a variable is unnecessary if we can use its value and directly compute a one time calculation, if the value will be used more than once, then a variable is necessary and from my understanding, the author of the post wanted to minimize the lines of code therefore, I omitted whatever variables I consider to be unnecessary and replaced them with one line comprehension syntax which is faster and shorter.
              $endgroup$
              – emadboctor
              Aug 15 at 16:22






            • 1




              $begingroup$
              @emadboctor OP says that algorithm2 isn't as good because he struggles to read and understand the code. Algorithm2 is the one with fewer variables. Variables with useful names document themselves, even if they're only used once. That's why it's probably better to have more variables.
              $endgroup$
              – user2023861
              Aug 15 at 18:18













            4














            4










            4







            $begingroup$

            Docstrings:



            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


            When you define a function and include a docstring, it should be contained within triple quotes instead of # that is used for comments.



            Like this:



            def sum_square_difference(max_range):
            """ Explanation goes here """


            Regarding the syntax or how you write the code, you might do it in one line instead of the use of many unnecessary variables.



            Like this:



            def square_difference(upper_bound):
            """Return sum numbers squared - sum of squares in range upper_bound inclusive."""
            return sum(range(1, upper_bound + 1)) ** 2 - sum(x ** 2 for x in range(1, upper_bound + 1))


            You might want to check pep8 https://www.python.org/dev/peps/pep-0008/ - the official Python style guide.






            share|improve this answer









            $endgroup$



            Docstrings:



            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


            When you define a function and include a docstring, it should be contained within triple quotes instead of # that is used for comments.



            Like this:



            def sum_square_difference(max_range):
            """ Explanation goes here """


            Regarding the syntax or how you write the code, you might do it in one line instead of the use of many unnecessary variables.



            Like this:



            def square_difference(upper_bound):
            """Return sum numbers squared - sum of squares in range upper_bound inclusive."""
            return sum(range(1, upper_bound + 1)) ** 2 - sum(x ** 2 for x in range(1, upper_bound + 1))


            You might want to check pep8 https://www.python.org/dev/peps/pep-0008/ - the official Python style guide.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 14 at 22:19









            emadboctoremadboctor

            1,0672 silver badges16 bronze badges




            1,0672 silver badges16 bronze badges










            • 3




              $begingroup$
              I don't think I agree with the idea of removing the definition of the range, it is much clearer that the same range is used twice if you assign it to a variable first.
              $endgroup$
              – Turksarama
              Aug 15 at 6:13










            • $begingroup$
              If you're referring to the style guide, you should also limit your maximum line length to 79 characters. You can still have it as one expression, split over multiple lines.
              $endgroup$
              – maxb
              Aug 15 at 7:24










            • $begingroup$
              unnecessary variables can you explain this point? I think that in general code with more usefully-named variables is easier to maintain than long lines of code like yours
              $endgroup$
              – user2023861
              Aug 15 at 16:13










            • $begingroup$
              @user2023861 a variable is unnecessary if we can use its value and directly compute a one time calculation, if the value will be used more than once, then a variable is necessary and from my understanding, the author of the post wanted to minimize the lines of code therefore, I omitted whatever variables I consider to be unnecessary and replaced them with one line comprehension syntax which is faster and shorter.
              $endgroup$
              – emadboctor
              Aug 15 at 16:22






            • 1




              $begingroup$
              @emadboctor OP says that algorithm2 isn't as good because he struggles to read and understand the code. Algorithm2 is the one with fewer variables. Variables with useful names document themselves, even if they're only used once. That's why it's probably better to have more variables.
              $endgroup$
              – user2023861
              Aug 15 at 18:18












            • 3




              $begingroup$
              I don't think I agree with the idea of removing the definition of the range, it is much clearer that the same range is used twice if you assign it to a variable first.
              $endgroup$
              – Turksarama
              Aug 15 at 6:13










            • $begingroup$
              If you're referring to the style guide, you should also limit your maximum line length to 79 characters. You can still have it as one expression, split over multiple lines.
              $endgroup$
              – maxb
              Aug 15 at 7:24










            • $begingroup$
              unnecessary variables can you explain this point? I think that in general code with more usefully-named variables is easier to maintain than long lines of code like yours
              $endgroup$
              – user2023861
              Aug 15 at 16:13










            • $begingroup$
              @user2023861 a variable is unnecessary if we can use its value and directly compute a one time calculation, if the value will be used more than once, then a variable is necessary and from my understanding, the author of the post wanted to minimize the lines of code therefore, I omitted whatever variables I consider to be unnecessary and replaced them with one line comprehension syntax which is faster and shorter.
              $endgroup$
              – emadboctor
              Aug 15 at 16:22






            • 1




              $begingroup$
              @emadboctor OP says that algorithm2 isn't as good because he struggles to read and understand the code. Algorithm2 is the one with fewer variables. Variables with useful names document themselves, even if they're only used once. That's why it's probably better to have more variables.
              $endgroup$
              – user2023861
              Aug 15 at 18:18







            3




            3




            $begingroup$
            I don't think I agree with the idea of removing the definition of the range, it is much clearer that the same range is used twice if you assign it to a variable first.
            $endgroup$
            – Turksarama
            Aug 15 at 6:13




            $begingroup$
            I don't think I agree with the idea of removing the definition of the range, it is much clearer that the same range is used twice if you assign it to a variable first.
            $endgroup$
            – Turksarama
            Aug 15 at 6:13












            $begingroup$
            If you're referring to the style guide, you should also limit your maximum line length to 79 characters. You can still have it as one expression, split over multiple lines.
            $endgroup$
            – maxb
            Aug 15 at 7:24




            $begingroup$
            If you're referring to the style guide, you should also limit your maximum line length to 79 characters. You can still have it as one expression, split over multiple lines.
            $endgroup$
            – maxb
            Aug 15 at 7:24












            $begingroup$
            unnecessary variables can you explain this point? I think that in general code with more usefully-named variables is easier to maintain than long lines of code like yours
            $endgroup$
            – user2023861
            Aug 15 at 16:13




            $begingroup$
            unnecessary variables can you explain this point? I think that in general code with more usefully-named variables is easier to maintain than long lines of code like yours
            $endgroup$
            – user2023861
            Aug 15 at 16:13












            $begingroup$
            @user2023861 a variable is unnecessary if we can use its value and directly compute a one time calculation, if the value will be used more than once, then a variable is necessary and from my understanding, the author of the post wanted to minimize the lines of code therefore, I omitted whatever variables I consider to be unnecessary and replaced them with one line comprehension syntax which is faster and shorter.
            $endgroup$
            – emadboctor
            Aug 15 at 16:22




            $begingroup$
            @user2023861 a variable is unnecessary if we can use its value and directly compute a one time calculation, if the value will be used more than once, then a variable is necessary and from my understanding, the author of the post wanted to minimize the lines of code therefore, I omitted whatever variables I consider to be unnecessary and replaced them with one line comprehension syntax which is faster and shorter.
            $endgroup$
            – emadboctor
            Aug 15 at 16:22




            1




            1




            $begingroup$
            @emadboctor OP says that algorithm2 isn't as good because he struggles to read and understand the code. Algorithm2 is the one with fewer variables. Variables with useful names document themselves, even if they're only used once. That's why it's probably better to have more variables.
            $endgroup$
            – user2023861
            Aug 15 at 18:18




            $begingroup$
            @emadboctor OP says that algorithm2 isn't as good because he struggles to read and understand the code. Algorithm2 is the one with fewer variables. Variables with useful names document themselves, even if they're only used once. That's why it's probably better to have more variables.
            $endgroup$
            – user2023861
            Aug 15 at 18:18

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f226138%2fsum-square-difference-which-way-is-more-pythonic%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Grendel Contents Story Scholarship Depictions Notes References Navigation menu10.1093/notesj/gjn112Berserkeree

            Area configuration aggregation error after install Porto themeMagento 2.1 CE Installed but front/backend not loading/workingCSS not loading on page within Magento 2 pageCannot install module in Magento 2no commands defined in the “setup” namespace. in Magento2Magento 2: Static files are present but shows 404Why do i have to always run the commands to clean cache in Magento 2.1.8?Failure reason: 'Unable to unserialize value.'Error 500 after magento migrationIn production mode the site does not loadMagento 2 : Error 500 after installing

            Middle Expansion Olielle Resaix Definition: Uttering songs of triumph shouting with joy triumphant exulting Sejunction Journal 붙다 달 고급 품목 외출 The stretch trades the screeching tin. Definition: The act of speaking with a drawl a drawl Cough Sand Definition: An uproar a quarrel a noisy outbreak Shake Iron Publicize Horse House Baby 사과 Resaix Flaggy Jelly Temporary Unequaled Puppet A drop in the bucket Shrew 성격 회원 성질 미팅 The burn frames the tacky quality. Materialistic The smoke reduces the way. Yammoe Nondescript Cheek 얼굴 배 약하다 날리다 타다 The illegal country shows the iron. Help Rule Drearien Smoke Teaching Meaty Wasp Abraham Lincoln Jaws 진심 수리하다 Size Cork Idea Convert Think Lark John Lennon 거울 청소 군 추천하다 아이스크림