Second largest integer without .sorted











up vote
0
down vote

favorite












def second_largest(numbers):
first = 0
second = 0
for n in numbers:
if n > first:
first, second = n, first
elif first > n > second:
second = n
return second or None
print(second_largest([2,2,2,-2]))


When i run this code, output is None, but i need it to be -2 and also i cant use functions as .sorted and others for array. I think that problem is in second = 0 ,but i dont know how to fix it.










share|improve this question






















  • Can you use the built-in max() function?
    – martineau
    Nov 11 at 0:53










  • it says i cant modify input array so i am not sure
    – Martin
    Nov 11 at 0:56






  • 1




    Use elif n > second in place of elif first > n > second.
    – Fred Miller
    Nov 11 at 0:58






  • 1




    In that case, since it doesn't, using it should be OK.
    – martineau
    Nov 11 at 0:58












  • Instead of first = 0 and second = 0, you should set them both to the smallest value supported by their datatype (e.g. -65536 for shorts)
    – Alex
    Nov 11 at 2:26















up vote
0
down vote

favorite












def second_largest(numbers):
first = 0
second = 0
for n in numbers:
if n > first:
first, second = n, first
elif first > n > second:
second = n
return second or None
print(second_largest([2,2,2,-2]))


When i run this code, output is None, but i need it to be -2 and also i cant use functions as .sorted and others for array. I think that problem is in second = 0 ,but i dont know how to fix it.










share|improve this question






















  • Can you use the built-in max() function?
    – martineau
    Nov 11 at 0:53










  • it says i cant modify input array so i am not sure
    – Martin
    Nov 11 at 0:56






  • 1




    Use elif n > second in place of elif first > n > second.
    – Fred Miller
    Nov 11 at 0:58






  • 1




    In that case, since it doesn't, using it should be OK.
    – martineau
    Nov 11 at 0:58












  • Instead of first = 0 and second = 0, you should set them both to the smallest value supported by their datatype (e.g. -65536 for shorts)
    – Alex
    Nov 11 at 2:26













up vote
0
down vote

favorite









up vote
0
down vote

favorite











def second_largest(numbers):
first = 0
second = 0
for n in numbers:
if n > first:
first, second = n, first
elif first > n > second:
second = n
return second or None
print(second_largest([2,2,2,-2]))


When i run this code, output is None, but i need it to be -2 and also i cant use functions as .sorted and others for array. I think that problem is in second = 0 ,but i dont know how to fix it.










share|improve this question













def second_largest(numbers):
first = 0
second = 0
for n in numbers:
if n > first:
first, second = n, first
elif first > n > second:
second = n
return second or None
print(second_largest([2,2,2,-2]))


When i run this code, output is None, but i need it to be -2 and also i cant use functions as .sorted and others for array. I think that problem is in second = 0 ,but i dont know how to fix it.







python python-3.x






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 0:50









Martin

82




82












  • Can you use the built-in max() function?
    – martineau
    Nov 11 at 0:53










  • it says i cant modify input array so i am not sure
    – Martin
    Nov 11 at 0:56






  • 1




    Use elif n > second in place of elif first > n > second.
    – Fred Miller
    Nov 11 at 0:58






  • 1




    In that case, since it doesn't, using it should be OK.
    – martineau
    Nov 11 at 0:58












  • Instead of first = 0 and second = 0, you should set them both to the smallest value supported by their datatype (e.g. -65536 for shorts)
    – Alex
    Nov 11 at 2:26


















  • Can you use the built-in max() function?
    – martineau
    Nov 11 at 0:53










  • it says i cant modify input array so i am not sure
    – Martin
    Nov 11 at 0:56






  • 1




    Use elif n > second in place of elif first > n > second.
    – Fred Miller
    Nov 11 at 0:58






  • 1




    In that case, since it doesn't, using it should be OK.
    – martineau
    Nov 11 at 0:58












  • Instead of first = 0 and second = 0, you should set them both to the smallest value supported by their datatype (e.g. -65536 for shorts)
    – Alex
    Nov 11 at 2:26
















Can you use the built-in max() function?
– martineau
Nov 11 at 0:53




Can you use the built-in max() function?
– martineau
Nov 11 at 0:53












it says i cant modify input array so i am not sure
– Martin
Nov 11 at 0:56




it says i cant modify input array so i am not sure
– Martin
Nov 11 at 0:56




1




1




Use elif n > second in place of elif first > n > second.
– Fred Miller
Nov 11 at 0:58




Use elif n > second in place of elif first > n > second.
– Fred Miller
Nov 11 at 0:58




1




1




In that case, since it doesn't, using it should be OK.
– martineau
Nov 11 at 0:58






In that case, since it doesn't, using it should be OK.
– martineau
Nov 11 at 0:58














Instead of first = 0 and second = 0, you should set them both to the smallest value supported by their datatype (e.g. -65536 for shorts)
– Alex
Nov 11 at 2:26




Instead of first = 0 and second = 0, you should set them both to the smallest value supported by their datatype (e.g. -65536 for shorts)
– Alex
Nov 11 at 2:26












4 Answers
4






active

oldest

votes

















up vote
3
down vote













Here's a few issues I see.




  1. You are instantiating first and second incorrectly (what if the largest number is negative)?

  2. The only time you'd want to return None is if your list size is smaller than 2.

  3. Change your return condition to return second.




def second_largest(numbers):
if len(numbers) < 2:
return None

first, second = numbers[0], numbers[1]
if first < second:
first, second = second, first

for n in numbers[2:]:
if n > first:
first, second = n, first
elif n > second:
second = n

return second





share|improve this answer






























    up vote
    0
    down vote













    Not sure if this is what you're looking for, but you can basically take the largest element out of the list (or make a note of it) and then search for the second-largest element in what's left. Here, I do this by first using max() (a built-in function of python that works on any iterable object) to get the largest element of the list, then using a list comprehension to create a second list of elements that do not equal that largest element, and finally using max() again to get the second-largest element from the original list.



    def second_largest(numbers):
    first = max(numbers)
    second = max([i for i in numbers if i != first])
    return second


    You could use a for loop for this if you didn't want to use max() for some reason.






    share|improve this answer




























      up vote
      0
      down vote













      The code you provided does not handle cases where n == first. Changing elif first > n > second to elif n > second should be sufficient (you do not need to test if first >= n since if control can reach that line n > first must be false).






      share|improve this answer




























        up vote
        0
        down vote













        Not use sorted?



        values = [2,2,2,-2]
        values.sort(reverse=True) # technically correct
        second_largest = values[1]


        or, less facetious



        values = set([2,2,2,-2])
        values.remove(max(values))
        second_largest = max(values)


        Or even



        import heapq
        heapq.nlargest(2, [2,2,2,-2])





        share|improve this answer























        • Fair enough but this isn't the point of OP's homework.
          – coldspeed
          Nov 11 at 10:31










        • It was not clear to me that this is homework. If someone is googling this problem and exclusively gets homework solutions rather than, say, heapq then they're going to have a sad time.
          – rikAtee
          Nov 11 at 10:45











        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: "1"
        };
        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',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        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%2fstackoverflow.com%2fquestions%2f53244868%2fsecond-largest-integer-without-sorted%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








        up vote
        3
        down vote













        Here's a few issues I see.




        1. You are instantiating first and second incorrectly (what if the largest number is negative)?

        2. The only time you'd want to return None is if your list size is smaller than 2.

        3. Change your return condition to return second.




        def second_largest(numbers):
        if len(numbers) < 2:
        return None

        first, second = numbers[0], numbers[1]
        if first < second:
        first, second = second, first

        for n in numbers[2:]:
        if n > first:
        first, second = n, first
        elif n > second:
        second = n

        return second





        share|improve this answer



























          up vote
          3
          down vote













          Here's a few issues I see.




          1. You are instantiating first and second incorrectly (what if the largest number is negative)?

          2. The only time you'd want to return None is if your list size is smaller than 2.

          3. Change your return condition to return second.




          def second_largest(numbers):
          if len(numbers) < 2:
          return None

          first, second = numbers[0], numbers[1]
          if first < second:
          first, second = second, first

          for n in numbers[2:]:
          if n > first:
          first, second = n, first
          elif n > second:
          second = n

          return second





          share|improve this answer

























            up vote
            3
            down vote










            up vote
            3
            down vote









            Here's a few issues I see.




            1. You are instantiating first and second incorrectly (what if the largest number is negative)?

            2. The only time you'd want to return None is if your list size is smaller than 2.

            3. Change your return condition to return second.




            def second_largest(numbers):
            if len(numbers) < 2:
            return None

            first, second = numbers[0], numbers[1]
            if first < second:
            first, second = second, first

            for n in numbers[2:]:
            if n > first:
            first, second = n, first
            elif n > second:
            second = n

            return second





            share|improve this answer














            Here's a few issues I see.




            1. You are instantiating first and second incorrectly (what if the largest number is negative)?

            2. The only time you'd want to return None is if your list size is smaller than 2.

            3. Change your return condition to return second.




            def second_largest(numbers):
            if len(numbers) < 2:
            return None

            first, second = numbers[0], numbers[1]
            if first < second:
            first, second = second, first

            for n in numbers[2:]:
            if n > first:
            first, second = n, first
            elif n > second:
            second = n

            return second






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 11 at 1:05

























            answered Nov 11 at 0:59









            coldspeed

            111k17100169




            111k17100169
























                up vote
                0
                down vote













                Not sure if this is what you're looking for, but you can basically take the largest element out of the list (or make a note of it) and then search for the second-largest element in what's left. Here, I do this by first using max() (a built-in function of python that works on any iterable object) to get the largest element of the list, then using a list comprehension to create a second list of elements that do not equal that largest element, and finally using max() again to get the second-largest element from the original list.



                def second_largest(numbers):
                first = max(numbers)
                second = max([i for i in numbers if i != first])
                return second


                You could use a for loop for this if you didn't want to use max() for some reason.






                share|improve this answer

























                  up vote
                  0
                  down vote













                  Not sure if this is what you're looking for, but you can basically take the largest element out of the list (or make a note of it) and then search for the second-largest element in what's left. Here, I do this by first using max() (a built-in function of python that works on any iterable object) to get the largest element of the list, then using a list comprehension to create a second list of elements that do not equal that largest element, and finally using max() again to get the second-largest element from the original list.



                  def second_largest(numbers):
                  first = max(numbers)
                  second = max([i for i in numbers if i != first])
                  return second


                  You could use a for loop for this if you didn't want to use max() for some reason.






                  share|improve this answer























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    Not sure if this is what you're looking for, but you can basically take the largest element out of the list (or make a note of it) and then search for the second-largest element in what's left. Here, I do this by first using max() (a built-in function of python that works on any iterable object) to get the largest element of the list, then using a list comprehension to create a second list of elements that do not equal that largest element, and finally using max() again to get the second-largest element from the original list.



                    def second_largest(numbers):
                    first = max(numbers)
                    second = max([i for i in numbers if i != first])
                    return second


                    You could use a for loop for this if you didn't want to use max() for some reason.






                    share|improve this answer












                    Not sure if this is what you're looking for, but you can basically take the largest element out of the list (or make a note of it) and then search for the second-largest element in what's left. Here, I do this by first using max() (a built-in function of python that works on any iterable object) to get the largest element of the list, then using a list comprehension to create a second list of elements that do not equal that largest element, and finally using max() again to get the second-largest element from the original list.



                    def second_largest(numbers):
                    first = max(numbers)
                    second = max([i for i in numbers if i != first])
                    return second


                    You could use a for loop for this if you didn't want to use max() for some reason.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 11 at 0:55









                    Green Cloak Guy

                    2,188720




                    2,188720






















                        up vote
                        0
                        down vote













                        The code you provided does not handle cases where n == first. Changing elif first > n > second to elif n > second should be sufficient (you do not need to test if first >= n since if control can reach that line n > first must be false).






                        share|improve this answer

























                          up vote
                          0
                          down vote













                          The code you provided does not handle cases where n == first. Changing elif first > n > second to elif n > second should be sufficient (you do not need to test if first >= n since if control can reach that line n > first must be false).






                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            The code you provided does not handle cases where n == first. Changing elif first > n > second to elif n > second should be sufficient (you do not need to test if first >= n since if control can reach that line n > first must be false).






                            share|improve this answer












                            The code you provided does not handle cases where n == first. Changing elif first > n > second to elif n > second should be sufficient (you do not need to test if first >= n since if control can reach that line n > first must be false).







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 11 at 1:04









                            Fred Miller

                            606315




                            606315






















                                up vote
                                0
                                down vote













                                Not use sorted?



                                values = [2,2,2,-2]
                                values.sort(reverse=True) # technically correct
                                second_largest = values[1]


                                or, less facetious



                                values = set([2,2,2,-2])
                                values.remove(max(values))
                                second_largest = max(values)


                                Or even



                                import heapq
                                heapq.nlargest(2, [2,2,2,-2])





                                share|improve this answer























                                • Fair enough but this isn't the point of OP's homework.
                                  – coldspeed
                                  Nov 11 at 10:31










                                • It was not clear to me that this is homework. If someone is googling this problem and exclusively gets homework solutions rather than, say, heapq then they're going to have a sad time.
                                  – rikAtee
                                  Nov 11 at 10:45















                                up vote
                                0
                                down vote













                                Not use sorted?



                                values = [2,2,2,-2]
                                values.sort(reverse=True) # technically correct
                                second_largest = values[1]


                                or, less facetious



                                values = set([2,2,2,-2])
                                values.remove(max(values))
                                second_largest = max(values)


                                Or even



                                import heapq
                                heapq.nlargest(2, [2,2,2,-2])





                                share|improve this answer























                                • Fair enough but this isn't the point of OP's homework.
                                  – coldspeed
                                  Nov 11 at 10:31










                                • It was not clear to me that this is homework. If someone is googling this problem and exclusively gets homework solutions rather than, say, heapq then they're going to have a sad time.
                                  – rikAtee
                                  Nov 11 at 10:45













                                up vote
                                0
                                down vote










                                up vote
                                0
                                down vote









                                Not use sorted?



                                values = [2,2,2,-2]
                                values.sort(reverse=True) # technically correct
                                second_largest = values[1]


                                or, less facetious



                                values = set([2,2,2,-2])
                                values.remove(max(values))
                                second_largest = max(values)


                                Or even



                                import heapq
                                heapq.nlargest(2, [2,2,2,-2])





                                share|improve this answer














                                Not use sorted?



                                values = [2,2,2,-2]
                                values.sort(reverse=True) # technically correct
                                second_largest = values[1]


                                or, less facetious



                                values = set([2,2,2,-2])
                                values.remove(max(values))
                                second_largest = max(values)


                                Or even



                                import heapq
                                heapq.nlargest(2, [2,2,2,-2])






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Nov 11 at 1:45

























                                answered Nov 11 at 1:38









                                rikAtee

                                4,59842855




                                4,59842855












                                • Fair enough but this isn't the point of OP's homework.
                                  – coldspeed
                                  Nov 11 at 10:31










                                • It was not clear to me that this is homework. If someone is googling this problem and exclusively gets homework solutions rather than, say, heapq then they're going to have a sad time.
                                  – rikAtee
                                  Nov 11 at 10:45


















                                • Fair enough but this isn't the point of OP's homework.
                                  – coldspeed
                                  Nov 11 at 10:31










                                • It was not clear to me that this is homework. If someone is googling this problem and exclusively gets homework solutions rather than, say, heapq then they're going to have a sad time.
                                  – rikAtee
                                  Nov 11 at 10:45
















                                Fair enough but this isn't the point of OP's homework.
                                – coldspeed
                                Nov 11 at 10:31




                                Fair enough but this isn't the point of OP's homework.
                                – coldspeed
                                Nov 11 at 10:31












                                It was not clear to me that this is homework. If someone is googling this problem and exclusively gets homework solutions rather than, say, heapq then they're going to have a sad time.
                                – rikAtee
                                Nov 11 at 10:45




                                It was not clear to me that this is homework. If someone is googling this problem and exclusively gets homework solutions rather than, say, heapq then they're going to have a sad time.
                                – rikAtee
                                Nov 11 at 10:45


















                                 

                                draft saved


                                draft discarded



















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53244868%2fsecond-largest-integer-without-sorted%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

                                Bressuire

                                Vorschmack

                                Quarantine