Sum Square Difference, which way is more Pythonic?Maintaining the Single Responsibility Principle with...

Insert or push_back to end of a std::vector?

How to prevent criminal gangs from making/buying guns?

A Magic Diamond

What would it take to get a message to another star?

What is the opposite of "hunger level"?

How to gracefully leave a company you helped start?

Is there any official ruling on how characters go from 0th to 1st level in a class?

What exactly happened to the 18 crew members who were reported as "missing" in "Q Who"?

Does the Haste spell's hasted action allow you to make multiple unarmed strikes? Or none at all?

What does 〇〇〇〇 mean when combined with おじさん?

If a person claims to know anything could it be disproven by saying 'prove that we are not in a simulation'?

Why are electric shavers specifically permitted under FAR §91.21

Why do we use low resistance cables to minimize power losses?

Adding things to bunches of things vs multiplication

Is Thieves' Cant a language?

What is the question mark?

Did Pope Urban II issue the papal bull "terra nullius" in 1095?

Why don't modern jet engines use forced exhaust mixing?

Does Reckless Attack work with Multiattack when wild shaped?

Scam? Phone call from "Department of Social Security" asking me to call back

When did Bilbo and Frodo learn that Gandalf was a Maia?

Quick destruction of a helium filled airship?

Why does Japan use the same type of AC power outlet as the US?

What's the point of writing that I know will never be used or read?



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;
}







9












$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









New contributor



takethelongsh0t is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$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
    2 hours ago




















9












$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









New contributor



takethelongsh0t is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$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
    2 hours ago
















9












9








9





$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









New contributor



takethelongsh0t is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$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









New contributor



takethelongsh0t is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.










share|improve this question









New contributor



takethelongsh0t is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








share|improve this question




share|improve this question








edited yesterday









dfhwze

8,5511 gold badge19 silver badges51 bronze badges




8,5511 gold badge19 silver badges51 bronze badges






New contributor



takethelongsh0t is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








asked yesterday









takethelongsh0ttakethelongsh0t

515 bronze badges




515 bronze badges




New contributor



takethelongsh0t is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




New contributor




takethelongsh0t is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.













  • 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
    2 hours ago
















  • 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
    2 hours ago










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
2 hours ago






$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
2 hours ago












4 Answers
4






active

oldest

votes


















15












$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








New contributor



Nikos Oikou is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





$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
    yesterday










  • $begingroup$
    @Turksarama With a decent editor (that supports highlighting), certainly you can.
    $endgroup$
    – Kenneth K.
    yesterday










  • $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
    7 hours ago





















14












$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$























    8












    $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$











    • 1




      $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
      13 hours ago












    • $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
      13 hours ago










    • $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
      7 hours ago










    • $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
      7 hours ago



















    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
      yesterday










    • $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
      yesterday










    • $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
      yesterday










    • $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
      yesterday






    • 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
      yesterday














    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
    });


    }
    });






    takethelongsh0t is a new contributor. Be nice, and check out our Code of Conduct.










    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









    15












    $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








    New contributor



    Nikos Oikou is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





    $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
      yesterday










    • $begingroup$
      @Turksarama With a decent editor (that supports highlighting), certainly you can.
      $endgroup$
      – Kenneth K.
      yesterday










    • $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
      7 hours ago


















    15












    $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








    New contributor



    Nikos Oikou is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





    $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
      yesterday










    • $begingroup$
      @Turksarama With a decent editor (that supports highlighting), certainly you can.
      $endgroup$
      – Kenneth K.
      yesterday










    • $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
      7 hours ago
















    15












    15








    15





    $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








    New contributor



    Nikos Oikou is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





    $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








    New contributor



    Nikos Oikou is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.








    share|improve this answer



    share|improve this answer






    New contributor



    Nikos Oikou is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.








    answered yesterday









    Nikos OikouNikos Oikou

    1663 bronze badges




    1663 bronze badges




    New contributor



    Nikos Oikou is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.




    New contributor




    Nikos Oikou is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.













    • 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
      yesterday










    • $begingroup$
      @Turksarama With a decent editor (that supports highlighting), certainly you can.
      $endgroup$
      – Kenneth K.
      yesterday










    • $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
      7 hours ago
















    • 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
      yesterday










    • $begingroup$
      @Turksarama With a decent editor (that supports highlighting), certainly you can.
      $endgroup$
      – Kenneth K.
      yesterday










    • $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
      7 hours ago










    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
    yesterday




    $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
    yesterday












    $begingroup$
    @Turksarama With a decent editor (that supports highlighting), certainly you can.
    $endgroup$
    – Kenneth K.
    yesterday




    $begingroup$
    @Turksarama With a decent editor (that supports highlighting), certainly you can.
    $endgroup$
    – Kenneth K.
    yesterday












    $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
    7 hours ago






    $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
    7 hours ago















    14












    $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$




















      14












      $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$


















        14












        14








        14





        $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 yesterday









        RootTwoRootTwo

        1,5093 silver badges9 bronze badges




        1,5093 silver badges9 bronze badges


























            8












            $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$











            • 1




              $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
              13 hours ago












            • $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
              13 hours ago










            • $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
              7 hours ago










            • $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
              7 hours ago
















            8












            $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$











            • 1




              $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
              13 hours ago












            • $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
              13 hours ago










            • $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
              7 hours ago










            • $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
              7 hours ago














            8












            8








            8





            $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 yesterday









            maxbmaxb

            1,2924 silver badges16 bronze badges




            1,2924 silver badges16 bronze badges











            • 1




              $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
              13 hours ago












            • $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
              13 hours ago










            • $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
              7 hours ago










            • $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
              7 hours ago














            • 1




              $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
              13 hours ago












            • $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
              13 hours ago










            • $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
              7 hours ago










            • $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
              7 hours ago








            1




            1




            $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
            13 hours ago






            $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
            13 hours ago














            $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
            13 hours ago




            $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
            13 hours ago












            $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
            7 hours ago




            $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
            7 hours ago












            $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
            7 hours ago




            $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
            7 hours ago











            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
              yesterday










            • $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
              yesterday










            • $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
              yesterday










            • $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
              yesterday






            • 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
              yesterday
















            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
              yesterday










            • $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
              yesterday










            • $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
              yesterday










            • $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
              yesterday






            • 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
              yesterday














            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 yesterday









            emadboctoremadboctor

            8162 silver badges13 bronze badges




            8162 silver badges13 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
              yesterday










            • $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
              yesterday










            • $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
              yesterday










            • $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
              yesterday






            • 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
              yesterday














            • 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
              yesterday










            • $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
              yesterday










            • $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
              yesterday










            • $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
              yesterday






            • 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
              yesterday








            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
            yesterday




            $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
            yesterday












            $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
            yesterday




            $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
            yesterday












            $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
            yesterday




            $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
            yesterday












            $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
            yesterday




            $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
            yesterday




            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
            yesterday




            $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
            yesterday










            takethelongsh0t is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            takethelongsh0t is a new contributor. Be nice, and check out our Code of Conduct.













            takethelongsh0t is a new contributor. Be nice, and check out our Code of Conduct.












            takethelongsh0t is a new contributor. Be nice, and check out our Code of Conduct.
















            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

            Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

            Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

            Nicolae Petrescu-Găină Cuprins Biografie | Opera | In memoriam | Varia | Controverse, incertitudini...