Count consecutive ones in a binary list











up vote
5
down vote

favorite
2












There is a list consisting of zeroes and ones. I want to find out the length of the longest streak of ones. Is there a better solution?



def consecutive_one(data):
one_list =
size = 0
for num in data:
if num == 1:
one_list.append(num)
elif num == 0 and size < len(one_list):
size = len(one_list)
one_list =

return size

if __name__ == '__main__':
data = [0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0]
print(consecutive_one(data))









share|improve this question




























    up vote
    5
    down vote

    favorite
    2












    There is a list consisting of zeroes and ones. I want to find out the length of the longest streak of ones. Is there a better solution?



    def consecutive_one(data):
    one_list =
    size = 0
    for num in data:
    if num == 1:
    one_list.append(num)
    elif num == 0 and size < len(one_list):
    size = len(one_list)
    one_list =

    return size

    if __name__ == '__main__':
    data = [0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0]
    print(consecutive_one(data))









    share|improve this question


























      up vote
      5
      down vote

      favorite
      2









      up vote
      5
      down vote

      favorite
      2






      2





      There is a list consisting of zeroes and ones. I want to find out the length of the longest streak of ones. Is there a better solution?



      def consecutive_one(data):
      one_list =
      size = 0
      for num in data:
      if num == 1:
      one_list.append(num)
      elif num == 0 and size < len(one_list):
      size = len(one_list)
      one_list =

      return size

      if __name__ == '__main__':
      data = [0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0]
      print(consecutive_one(data))









      share|improve this question















      There is a list consisting of zeroes and ones. I want to find out the length of the longest streak of ones. Is there a better solution?



      def consecutive_one(data):
      one_list =
      size = 0
      for num in data:
      if num == 1:
      one_list.append(num)
      elif num == 0 and size < len(one_list):
      size = len(one_list)
      one_list =

      return size

      if __name__ == '__main__':
      data = [0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0]
      print(consecutive_one(data))






      python programming-challenge






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Aug 13 '16 at 13:00









      200_success

      128k15149412




      128k15149412










      asked Aug 12 '16 at 15:53









      hizbul25

      12816




      12816






















          3 Answers
          3






          active

          oldest

          votes

















          up vote
          6
          down vote



          accepted










          Both your and janos' implementations are broken:



          data = [1, 0] * 10000
          consecutive_one(data)
          #>>> 140


          This is because you don't always reset after seeing a 0. Going from janos', you should have



          longest = 0
          current = 0
          for num in data:
          if num == 1:
          current += 1
          else:
          longest = max(longest, current)
          current = 0

          return max(longest, current)


          and equivalent for the original.



          You'll find that this functionality is largely provided by itertools.groupby, though:



          from itertools import groupby

          def len_iter(items):
          return sum(1 for _ in items)

          def consecutive_one(data):
          return max(len_iter(run) for val, run in groupby(data) if val)





          share|improve this answer






























            up vote
            6
            down vote













            You have a bug



            If the last value is a 1, and it is the end of the longest consecutive sequence, it won't be taken into account.
            The fix is to change the return statement to this:



            return max(size, len(one_list))


            Unnecessary condition



            If you know your input only contains 0 and 1 values,
            then you can simplify this condition:




            if num == 1:
            # ...
            elif num == 0 and size < len(one_list):
            # ...



            By dropping the num == 0:




            if num == 1:
            # ...
            elif size < len(one_list):
            # ...



            But note that this is not good enough, as there's still a bug hiding there as @veedrac explains in his answer, instead of an elif, this should be rewritten using an else.



            Improving storage efficiency



            There's no need to store the 1s as you count them.
            You can just keep the count in a variable.



            Testing



            Instead of running your function using test data,
            give a try to doctests, like this:



            def consecutive_one(data):
            """
            >>> consecutive_one([0, 1, 0, 1, 1, 0])
            2
            >>> consecutive_one([0, 1, 0, 1, 1, 1])
            3
            >>> consecutive_one([0, 1] * 10)
            1
            """
            # ... the implementation ...


            To run all doctests within a file, run python -m doctest yourfile.py.
            When all tests pass, there is no output.
            When something fails you will get a detailed report.
            This is an excellent way to test your implementation,
            and also to document usage with examples and expected outputs.






            share|improve this answer



















            • 2




              Just to be more precise, he doesn't have to know that the list contains only 0 and 1. The purpose is to count every 1, so it's not really relevant if it's 0 or another character, as long as it's not 1.
              – ChatterOne
              Aug 12 '16 at 20:48


















            up vote
            0
            down vote













            You have a bug on elif statement size < len(one_list):



            if __name__ == '__main__':
            n = int(input())

            binary = [int(x) for x in bin(n)[2:]]

            one_list =
            size = 0

            for num in binary:
            if num == 1:
            one_list.append(num)

            if size < len(one_list):
            size = len(one_list)

            elif num == 0 :
            one_list.clear()

            print(size)





            share|improve this answer










            New contributor




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


















            • (Welcome to Code Review!) (While valid, this has been stated before.)
              – greybeard
              9 hours ago











            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

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


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f138550%2fcount-consecutive-ones-in-a-binary-list%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            6
            down vote



            accepted










            Both your and janos' implementations are broken:



            data = [1, 0] * 10000
            consecutive_one(data)
            #>>> 140


            This is because you don't always reset after seeing a 0. Going from janos', you should have



            longest = 0
            current = 0
            for num in data:
            if num == 1:
            current += 1
            else:
            longest = max(longest, current)
            current = 0

            return max(longest, current)


            and equivalent for the original.



            You'll find that this functionality is largely provided by itertools.groupby, though:



            from itertools import groupby

            def len_iter(items):
            return sum(1 for _ in items)

            def consecutive_one(data):
            return max(len_iter(run) for val, run in groupby(data) if val)





            share|improve this answer



























              up vote
              6
              down vote



              accepted










              Both your and janos' implementations are broken:



              data = [1, 0] * 10000
              consecutive_one(data)
              #>>> 140


              This is because you don't always reset after seeing a 0. Going from janos', you should have



              longest = 0
              current = 0
              for num in data:
              if num == 1:
              current += 1
              else:
              longest = max(longest, current)
              current = 0

              return max(longest, current)


              and equivalent for the original.



              You'll find that this functionality is largely provided by itertools.groupby, though:



              from itertools import groupby

              def len_iter(items):
              return sum(1 for _ in items)

              def consecutive_one(data):
              return max(len_iter(run) for val, run in groupby(data) if val)





              share|improve this answer

























                up vote
                6
                down vote



                accepted







                up vote
                6
                down vote



                accepted






                Both your and janos' implementations are broken:



                data = [1, 0] * 10000
                consecutive_one(data)
                #>>> 140


                This is because you don't always reset after seeing a 0. Going from janos', you should have



                longest = 0
                current = 0
                for num in data:
                if num == 1:
                current += 1
                else:
                longest = max(longest, current)
                current = 0

                return max(longest, current)


                and equivalent for the original.



                You'll find that this functionality is largely provided by itertools.groupby, though:



                from itertools import groupby

                def len_iter(items):
                return sum(1 for _ in items)

                def consecutive_one(data):
                return max(len_iter(run) for val, run in groupby(data) if val)





                share|improve this answer














                Both your and janos' implementations are broken:



                data = [1, 0] * 10000
                consecutive_one(data)
                #>>> 140


                This is because you don't always reset after seeing a 0. Going from janos', you should have



                longest = 0
                current = 0
                for num in data:
                if num == 1:
                current += 1
                else:
                longest = max(longest, current)
                current = 0

                return max(longest, current)


                and equivalent for the original.



                You'll find that this functionality is largely provided by itertools.groupby, though:



                from itertools import groupby

                def len_iter(items):
                return sum(1 for _ in items)

                def consecutive_one(data):
                return max(len_iter(run) for val, run in groupby(data) if val)






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Aug 13 '16 at 13:01









                200_success

                128k15149412




                128k15149412










                answered Aug 12 '16 at 22:48









                Veedrac

                9,0731634




                9,0731634
























                    up vote
                    6
                    down vote













                    You have a bug



                    If the last value is a 1, and it is the end of the longest consecutive sequence, it won't be taken into account.
                    The fix is to change the return statement to this:



                    return max(size, len(one_list))


                    Unnecessary condition



                    If you know your input only contains 0 and 1 values,
                    then you can simplify this condition:




                    if num == 1:
                    # ...
                    elif num == 0 and size < len(one_list):
                    # ...



                    By dropping the num == 0:




                    if num == 1:
                    # ...
                    elif size < len(one_list):
                    # ...



                    But note that this is not good enough, as there's still a bug hiding there as @veedrac explains in his answer, instead of an elif, this should be rewritten using an else.



                    Improving storage efficiency



                    There's no need to store the 1s as you count them.
                    You can just keep the count in a variable.



                    Testing



                    Instead of running your function using test data,
                    give a try to doctests, like this:



                    def consecutive_one(data):
                    """
                    >>> consecutive_one([0, 1, 0, 1, 1, 0])
                    2
                    >>> consecutive_one([0, 1, 0, 1, 1, 1])
                    3
                    >>> consecutive_one([0, 1] * 10)
                    1
                    """
                    # ... the implementation ...


                    To run all doctests within a file, run python -m doctest yourfile.py.
                    When all tests pass, there is no output.
                    When something fails you will get a detailed report.
                    This is an excellent way to test your implementation,
                    and also to document usage with examples and expected outputs.






                    share|improve this answer



















                    • 2




                      Just to be more precise, he doesn't have to know that the list contains only 0 and 1. The purpose is to count every 1, so it's not really relevant if it's 0 or another character, as long as it's not 1.
                      – ChatterOne
                      Aug 12 '16 at 20:48















                    up vote
                    6
                    down vote













                    You have a bug



                    If the last value is a 1, and it is the end of the longest consecutive sequence, it won't be taken into account.
                    The fix is to change the return statement to this:



                    return max(size, len(one_list))


                    Unnecessary condition



                    If you know your input only contains 0 and 1 values,
                    then you can simplify this condition:




                    if num == 1:
                    # ...
                    elif num == 0 and size < len(one_list):
                    # ...



                    By dropping the num == 0:




                    if num == 1:
                    # ...
                    elif size < len(one_list):
                    # ...



                    But note that this is not good enough, as there's still a bug hiding there as @veedrac explains in his answer, instead of an elif, this should be rewritten using an else.



                    Improving storage efficiency



                    There's no need to store the 1s as you count them.
                    You can just keep the count in a variable.



                    Testing



                    Instead of running your function using test data,
                    give a try to doctests, like this:



                    def consecutive_one(data):
                    """
                    >>> consecutive_one([0, 1, 0, 1, 1, 0])
                    2
                    >>> consecutive_one([0, 1, 0, 1, 1, 1])
                    3
                    >>> consecutive_one([0, 1] * 10)
                    1
                    """
                    # ... the implementation ...


                    To run all doctests within a file, run python -m doctest yourfile.py.
                    When all tests pass, there is no output.
                    When something fails you will get a detailed report.
                    This is an excellent way to test your implementation,
                    and also to document usage with examples and expected outputs.






                    share|improve this answer



















                    • 2




                      Just to be more precise, he doesn't have to know that the list contains only 0 and 1. The purpose is to count every 1, so it's not really relevant if it's 0 or another character, as long as it's not 1.
                      – ChatterOne
                      Aug 12 '16 at 20:48













                    up vote
                    6
                    down vote










                    up vote
                    6
                    down vote









                    You have a bug



                    If the last value is a 1, and it is the end of the longest consecutive sequence, it won't be taken into account.
                    The fix is to change the return statement to this:



                    return max(size, len(one_list))


                    Unnecessary condition



                    If you know your input only contains 0 and 1 values,
                    then you can simplify this condition:




                    if num == 1:
                    # ...
                    elif num == 0 and size < len(one_list):
                    # ...



                    By dropping the num == 0:




                    if num == 1:
                    # ...
                    elif size < len(one_list):
                    # ...



                    But note that this is not good enough, as there's still a bug hiding there as @veedrac explains in his answer, instead of an elif, this should be rewritten using an else.



                    Improving storage efficiency



                    There's no need to store the 1s as you count them.
                    You can just keep the count in a variable.



                    Testing



                    Instead of running your function using test data,
                    give a try to doctests, like this:



                    def consecutive_one(data):
                    """
                    >>> consecutive_one([0, 1, 0, 1, 1, 0])
                    2
                    >>> consecutive_one([0, 1, 0, 1, 1, 1])
                    3
                    >>> consecutive_one([0, 1] * 10)
                    1
                    """
                    # ... the implementation ...


                    To run all doctests within a file, run python -m doctest yourfile.py.
                    When all tests pass, there is no output.
                    When something fails you will get a detailed report.
                    This is an excellent way to test your implementation,
                    and also to document usage with examples and expected outputs.






                    share|improve this answer














                    You have a bug



                    If the last value is a 1, and it is the end of the longest consecutive sequence, it won't be taken into account.
                    The fix is to change the return statement to this:



                    return max(size, len(one_list))


                    Unnecessary condition



                    If you know your input only contains 0 and 1 values,
                    then you can simplify this condition:




                    if num == 1:
                    # ...
                    elif num == 0 and size < len(one_list):
                    # ...



                    By dropping the num == 0:




                    if num == 1:
                    # ...
                    elif size < len(one_list):
                    # ...



                    But note that this is not good enough, as there's still a bug hiding there as @veedrac explains in his answer, instead of an elif, this should be rewritten using an else.



                    Improving storage efficiency



                    There's no need to store the 1s as you count them.
                    You can just keep the count in a variable.



                    Testing



                    Instead of running your function using test data,
                    give a try to doctests, like this:



                    def consecutive_one(data):
                    """
                    >>> consecutive_one([0, 1, 0, 1, 1, 0])
                    2
                    >>> consecutive_one([0, 1, 0, 1, 1, 1])
                    3
                    >>> consecutive_one([0, 1] * 10)
                    1
                    """
                    # ... the implementation ...


                    To run all doctests within a file, run python -m doctest yourfile.py.
                    When all tests pass, there is no output.
                    When something fails you will get a detailed report.
                    This is an excellent way to test your implementation,
                    and also to document usage with examples and expected outputs.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Aug 13 '16 at 6:04

























                    answered Aug 12 '16 at 18:59









                    janos

                    96.7k12124350




                    96.7k12124350








                    • 2




                      Just to be more precise, he doesn't have to know that the list contains only 0 and 1. The purpose is to count every 1, so it's not really relevant if it's 0 or another character, as long as it's not 1.
                      – ChatterOne
                      Aug 12 '16 at 20:48














                    • 2




                      Just to be more precise, he doesn't have to know that the list contains only 0 and 1. The purpose is to count every 1, so it's not really relevant if it's 0 or another character, as long as it's not 1.
                      – ChatterOne
                      Aug 12 '16 at 20:48








                    2




                    2




                    Just to be more precise, he doesn't have to know that the list contains only 0 and 1. The purpose is to count every 1, so it's not really relevant if it's 0 or another character, as long as it's not 1.
                    – ChatterOne
                    Aug 12 '16 at 20:48




                    Just to be more precise, he doesn't have to know that the list contains only 0 and 1. The purpose is to count every 1, so it's not really relevant if it's 0 or another character, as long as it's not 1.
                    – ChatterOne
                    Aug 12 '16 at 20:48










                    up vote
                    0
                    down vote













                    You have a bug on elif statement size < len(one_list):



                    if __name__ == '__main__':
                    n = int(input())

                    binary = [int(x) for x in bin(n)[2:]]

                    one_list =
                    size = 0

                    for num in binary:
                    if num == 1:
                    one_list.append(num)

                    if size < len(one_list):
                    size = len(one_list)

                    elif num == 0 :
                    one_list.clear()

                    print(size)





                    share|improve this answer










                    New contributor




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


















                    • (Welcome to Code Review!) (While valid, this has been stated before.)
                      – greybeard
                      9 hours ago















                    up vote
                    0
                    down vote













                    You have a bug on elif statement size < len(one_list):



                    if __name__ == '__main__':
                    n = int(input())

                    binary = [int(x) for x in bin(n)[2:]]

                    one_list =
                    size = 0

                    for num in binary:
                    if num == 1:
                    one_list.append(num)

                    if size < len(one_list):
                    size = len(one_list)

                    elif num == 0 :
                    one_list.clear()

                    print(size)





                    share|improve this answer










                    New contributor




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


















                    • (Welcome to Code Review!) (While valid, this has been stated before.)
                      – greybeard
                      9 hours ago













                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    You have a bug on elif statement size < len(one_list):



                    if __name__ == '__main__':
                    n = int(input())

                    binary = [int(x) for x in bin(n)[2:]]

                    one_list =
                    size = 0

                    for num in binary:
                    if num == 1:
                    one_list.append(num)

                    if size < len(one_list):
                    size = len(one_list)

                    elif num == 0 :
                    one_list.clear()

                    print(size)





                    share|improve this answer










                    New contributor




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









                    You have a bug on elif statement size < len(one_list):



                    if __name__ == '__main__':
                    n = int(input())

                    binary = [int(x) for x in bin(n)[2:]]

                    one_list =
                    size = 0

                    for num in binary:
                    if num == 1:
                    one_list.append(num)

                    if size < len(one_list):
                    size = len(one_list)

                    elif num == 0 :
                    one_list.clear()

                    print(size)






                    share|improve this answer










                    New contributor




                    Muhammad Usaam Abid 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








                    edited 10 hours ago









                    Sᴀᴍ Onᴇᴌᴀ

                    8,13861752




                    8,13861752






                    New contributor




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









                    answered 11 hours ago









                    Muhammad Usaam Abid

                    11




                    11




                    New contributor




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





                    New contributor





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






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












                    • (Welcome to Code Review!) (While valid, this has been stated before.)
                      – greybeard
                      9 hours ago


















                    • (Welcome to Code Review!) (While valid, this has been stated before.)
                      – greybeard
                      9 hours ago
















                    (Welcome to Code Review!) (While valid, this has been stated before.)
                    – greybeard
                    9 hours ago




                    (Welcome to Code Review!) (While valid, this has been stated before.)
                    – greybeard
                    9 hours ago


















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


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

                    But avoid



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

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


                    Use MathJax to format equations. MathJax reference.


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





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


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


                    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%2f138550%2fcount-consecutive-ones-in-a-binary-list%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

                    Quarter-circle Tiles

                    build a pushdown automaton that recognizes the reverse language of a given pushdown automaton?

                    Mont Emei