Count of consecutive elements in a list that satisfy a given condition





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















i have a list o lists of integers for example such a below:



list1 = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]


and i want to get maximum length of consecutive even numbers in each sublist as output,
output list is:



  olist = [1,2,3,0,3]


and this is my code:



olist=
for ii in list1:
if all(item % 2 == 0 for item in ii):
olist.append(len(ii))
print (olist)


but this code is wrong.










share|improve this question




















  • 3





    never a good idea to instantiate a list with name list, as it's a key word.

    – cph_sto
    Jan 4 at 10:22




















0















i have a list o lists of integers for example such a below:



list1 = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]


and i want to get maximum length of consecutive even numbers in each sublist as output,
output list is:



  olist = [1,2,3,0,3]


and this is my code:



olist=
for ii in list1:
if all(item % 2 == 0 for item in ii):
olist.append(len(ii))
print (olist)


but this code is wrong.










share|improve this question




















  • 3





    never a good idea to instantiate a list with name list, as it's a key word.

    – cph_sto
    Jan 4 at 10:22
















0












0








0








i have a list o lists of integers for example such a below:



list1 = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]


and i want to get maximum length of consecutive even numbers in each sublist as output,
output list is:



  olist = [1,2,3,0,3]


and this is my code:



olist=
for ii in list1:
if all(item % 2 == 0 for item in ii):
olist.append(len(ii))
print (olist)


but this code is wrong.










share|improve this question
















i have a list o lists of integers for example such a below:



list1 = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]


and i want to get maximum length of consecutive even numbers in each sublist as output,
output list is:



  olist = [1,2,3,0,3]


and this is my code:



olist=
for ii in list1:
if all(item % 2 == 0 for item in ii):
olist.append(len(ii))
print (olist)


but this code is wrong.







python list






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 4 at 10:58









coldspeed

142k25159247




142k25159247










asked Jan 4 at 10:18









get dataget data

545




545








  • 3





    never a good idea to instantiate a list with name list, as it's a key word.

    – cph_sto
    Jan 4 at 10:22
















  • 3





    never a good idea to instantiate a list with name list, as it's a key word.

    – cph_sto
    Jan 4 at 10:22










3




3





never a good idea to instantiate a list with name list, as it's a key word.

– cph_sto
Jan 4 at 10:22







never a good idea to instantiate a list with name list, as it's a key word.

– cph_sto
Jan 4 at 10:22














4 Answers
4






active

oldest

votes


















4














Let's keep this simple. You will need two loops. You will also need a counter to keep track of the current count. You can have tr keep track of the largest count, for simplicity.



tr = [0] * len(lst)
for i, l in enumerate(lst):
counter = 0
for v in l:
if v % 2 == 0:
counter += 1
else:
tr[i] = max(counter, tr[i])
counter = 0
tr[i] = max(counter, tr[i])

print(tr)
# [1, 2, 3, 0, 3]





share|improve this answer

































    3














    You can use itertools.groupby to group the numbers in even / odd groups then get the even group with maximum length using max:



    from itertools import groupby

    def max_even(lst):
    result =
    for e in lst:
    it = (sum(1 for _ in group) for k, group in groupby(e, lambda x: x % 2) if not k)
    m = max(it, default=0)
    result.append(m)
    return result

    l = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]

    res = max_even(l)
    print(res)


    Output



    [1, 2, 3, 0, 3]





    share|improve this answer































      1














      myList = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]
      outList =
      for i in myList:
      max_Length = 0
      myLength = 0
      interim_list =
      for j in i:
      if j%2 == 0:
      myLength = myLength + 1
      if myLength > max_Length:
      max_Length = myLength
      else:
      myLength = 0
      outList.append(max_Length)
      outList
      [1,2,3,0,3]





      share|improve this answer


























      • Why store all intermediate values when you could just store the maximum? This seems wasteful.

        – coldspeed
        Jan 4 at 10:39











      • Thanks Sir. Yes, the previous code was not efficient. I did the changes now. Feedback is always appreciated.

        – cph_sto
        Jan 4 at 10:45





















      0














      I'd define a helper method that can handle a condition:



      def max_consecutive(array, odd_even):
      remainder = {'odd':1,'even':0}
      count, max_count = 0, 0
      for e in array:
      if e%2 == remainder[odd_even]:
      count +=1
      else:
      count = 0
      max_count = max(count, max_count)
      return max_count


      To be used in a list comprehension:



      array = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]

      [max_consecutive(sub, 'even') for sub in array]
      #=> [1, 2, 3, 0, 3]

      [max_consecutive(sub, 'odd') for sub in array]
      #=> [1, 1, 2, 2, 1]





      share|improve this answer
























        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',
        autoActivateHeartbeat: false,
        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%2f54036956%2fcount-of-consecutive-elements-in-a-list-that-satisfy-a-given-condition%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









        4














        Let's keep this simple. You will need two loops. You will also need a counter to keep track of the current count. You can have tr keep track of the largest count, for simplicity.



        tr = [0] * len(lst)
        for i, l in enumerate(lst):
        counter = 0
        for v in l:
        if v % 2 == 0:
        counter += 1
        else:
        tr[i] = max(counter, tr[i])
        counter = 0
        tr[i] = max(counter, tr[i])

        print(tr)
        # [1, 2, 3, 0, 3]





        share|improve this answer






























          4














          Let's keep this simple. You will need two loops. You will also need a counter to keep track of the current count. You can have tr keep track of the largest count, for simplicity.



          tr = [0] * len(lst)
          for i, l in enumerate(lst):
          counter = 0
          for v in l:
          if v % 2 == 0:
          counter += 1
          else:
          tr[i] = max(counter, tr[i])
          counter = 0
          tr[i] = max(counter, tr[i])

          print(tr)
          # [1, 2, 3, 0, 3]





          share|improve this answer




























            4












            4








            4







            Let's keep this simple. You will need two loops. You will also need a counter to keep track of the current count. You can have tr keep track of the largest count, for simplicity.



            tr = [0] * len(lst)
            for i, l in enumerate(lst):
            counter = 0
            for v in l:
            if v % 2 == 0:
            counter += 1
            else:
            tr[i] = max(counter, tr[i])
            counter = 0
            tr[i] = max(counter, tr[i])

            print(tr)
            # [1, 2, 3, 0, 3]





            share|improve this answer















            Let's keep this simple. You will need two loops. You will also need a counter to keep track of the current count. You can have tr keep track of the largest count, for simplicity.



            tr = [0] * len(lst)
            for i, l in enumerate(lst):
            counter = 0
            for v in l:
            if v % 2 == 0:
            counter += 1
            else:
            tr[i] = max(counter, tr[i])
            counter = 0
            tr[i] = max(counter, tr[i])

            print(tr)
            # [1, 2, 3, 0, 3]






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 4 at 10:43

























            answered Jan 4 at 10:23









            coldspeedcoldspeed

            142k25159247




            142k25159247

























                3














                You can use itertools.groupby to group the numbers in even / odd groups then get the even group with maximum length using max:



                from itertools import groupby

                def max_even(lst):
                result =
                for e in lst:
                it = (sum(1 for _ in group) for k, group in groupby(e, lambda x: x % 2) if not k)
                m = max(it, default=0)
                result.append(m)
                return result

                l = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]

                res = max_even(l)
                print(res)


                Output



                [1, 2, 3, 0, 3]





                share|improve this answer




























                  3














                  You can use itertools.groupby to group the numbers in even / odd groups then get the even group with maximum length using max:



                  from itertools import groupby

                  def max_even(lst):
                  result =
                  for e in lst:
                  it = (sum(1 for _ in group) for k, group in groupby(e, lambda x: x % 2) if not k)
                  m = max(it, default=0)
                  result.append(m)
                  return result

                  l = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]

                  res = max_even(l)
                  print(res)


                  Output



                  [1, 2, 3, 0, 3]





                  share|improve this answer


























                    3












                    3








                    3







                    You can use itertools.groupby to group the numbers in even / odd groups then get the even group with maximum length using max:



                    from itertools import groupby

                    def max_even(lst):
                    result =
                    for e in lst:
                    it = (sum(1 for _ in group) for k, group in groupby(e, lambda x: x % 2) if not k)
                    m = max(it, default=0)
                    result.append(m)
                    return result

                    l = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]

                    res = max_even(l)
                    print(res)


                    Output



                    [1, 2, 3, 0, 3]





                    share|improve this answer













                    You can use itertools.groupby to group the numbers in even / odd groups then get the even group with maximum length using max:



                    from itertools import groupby

                    def max_even(lst):
                    result =
                    for e in lst:
                    it = (sum(1 for _ in group) for k, group in groupby(e, lambda x: x % 2) if not k)
                    m = max(it, default=0)
                    result.append(m)
                    return result

                    l = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]

                    res = max_even(l)
                    print(res)


                    Output



                    [1, 2, 3, 0, 3]






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 4 at 10:22









                    Daniel MesejoDaniel Mesejo

                    18.8k21533




                    18.8k21533























                        1














                        myList = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]
                        outList =
                        for i in myList:
                        max_Length = 0
                        myLength = 0
                        interim_list =
                        for j in i:
                        if j%2 == 0:
                        myLength = myLength + 1
                        if myLength > max_Length:
                        max_Length = myLength
                        else:
                        myLength = 0
                        outList.append(max_Length)
                        outList
                        [1,2,3,0,3]





                        share|improve this answer


























                        • Why store all intermediate values when you could just store the maximum? This seems wasteful.

                          – coldspeed
                          Jan 4 at 10:39











                        • Thanks Sir. Yes, the previous code was not efficient. I did the changes now. Feedback is always appreciated.

                          – cph_sto
                          Jan 4 at 10:45


















                        1














                        myList = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]
                        outList =
                        for i in myList:
                        max_Length = 0
                        myLength = 0
                        interim_list =
                        for j in i:
                        if j%2 == 0:
                        myLength = myLength + 1
                        if myLength > max_Length:
                        max_Length = myLength
                        else:
                        myLength = 0
                        outList.append(max_Length)
                        outList
                        [1,2,3,0,3]





                        share|improve this answer


























                        • Why store all intermediate values when you could just store the maximum? This seems wasteful.

                          – coldspeed
                          Jan 4 at 10:39











                        • Thanks Sir. Yes, the previous code was not efficient. I did the changes now. Feedback is always appreciated.

                          – cph_sto
                          Jan 4 at 10:45
















                        1












                        1








                        1







                        myList = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]
                        outList =
                        for i in myList:
                        max_Length = 0
                        myLength = 0
                        interim_list =
                        for j in i:
                        if j%2 == 0:
                        myLength = myLength + 1
                        if myLength > max_Length:
                        max_Length = myLength
                        else:
                        myLength = 0
                        outList.append(max_Length)
                        outList
                        [1,2,3,0,3]





                        share|improve this answer















                        myList = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]
                        outList =
                        for i in myList:
                        max_Length = 0
                        myLength = 0
                        interim_list =
                        for j in i:
                        if j%2 == 0:
                        myLength = myLength + 1
                        if myLength > max_Length:
                        max_Length = myLength
                        else:
                        myLength = 0
                        outList.append(max_Length)
                        outList
                        [1,2,3,0,3]






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jan 4 at 10:45

























                        answered Jan 4 at 10:33









                        cph_stocph_sto

                        2,6352524




                        2,6352524













                        • Why store all intermediate values when you could just store the maximum? This seems wasteful.

                          – coldspeed
                          Jan 4 at 10:39











                        • Thanks Sir. Yes, the previous code was not efficient. I did the changes now. Feedback is always appreciated.

                          – cph_sto
                          Jan 4 at 10:45





















                        • Why store all intermediate values when you could just store the maximum? This seems wasteful.

                          – coldspeed
                          Jan 4 at 10:39











                        • Thanks Sir. Yes, the previous code was not efficient. I did the changes now. Feedback is always appreciated.

                          – cph_sto
                          Jan 4 at 10:45



















                        Why store all intermediate values when you could just store the maximum? This seems wasteful.

                        – coldspeed
                        Jan 4 at 10:39





                        Why store all intermediate values when you could just store the maximum? This seems wasteful.

                        – coldspeed
                        Jan 4 at 10:39













                        Thanks Sir. Yes, the previous code was not efficient. I did the changes now. Feedback is always appreciated.

                        – cph_sto
                        Jan 4 at 10:45







                        Thanks Sir. Yes, the previous code was not efficient. I did the changes now. Feedback is always appreciated.

                        – cph_sto
                        Jan 4 at 10:45













                        0














                        I'd define a helper method that can handle a condition:



                        def max_consecutive(array, odd_even):
                        remainder = {'odd':1,'even':0}
                        count, max_count = 0, 0
                        for e in array:
                        if e%2 == remainder[odd_even]:
                        count +=1
                        else:
                        count = 0
                        max_count = max(count, max_count)
                        return max_count


                        To be used in a list comprehension:



                        array = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]

                        [max_consecutive(sub, 'even') for sub in array]
                        #=> [1, 2, 3, 0, 3]

                        [max_consecutive(sub, 'odd') for sub in array]
                        #=> [1, 1, 2, 2, 1]





                        share|improve this answer




























                          0














                          I'd define a helper method that can handle a condition:



                          def max_consecutive(array, odd_even):
                          remainder = {'odd':1,'even':0}
                          count, max_count = 0, 0
                          for e in array:
                          if e%2 == remainder[odd_even]:
                          count +=1
                          else:
                          count = 0
                          max_count = max(count, max_count)
                          return max_count


                          To be used in a list comprehension:



                          array = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]

                          [max_consecutive(sub, 'even') for sub in array]
                          #=> [1, 2, 3, 0, 3]

                          [max_consecutive(sub, 'odd') for sub in array]
                          #=> [1, 1, 2, 2, 1]





                          share|improve this answer


























                            0












                            0








                            0







                            I'd define a helper method that can handle a condition:



                            def max_consecutive(array, odd_even):
                            remainder = {'odd':1,'even':0}
                            count, max_count = 0, 0
                            for e in array:
                            if e%2 == remainder[odd_even]:
                            count +=1
                            else:
                            count = 0
                            max_count = max(count, max_count)
                            return max_count


                            To be used in a list comprehension:



                            array = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]

                            [max_consecutive(sub, 'even') for sub in array]
                            #=> [1, 2, 3, 0, 3]

                            [max_consecutive(sub, 'odd') for sub in array]
                            #=> [1, 1, 2, 2, 1]





                            share|improve this answer













                            I'd define a helper method that can handle a condition:



                            def max_consecutive(array, odd_even):
                            remainder = {'odd':1,'even':0}
                            count, max_count = 0, 0
                            for e in array:
                            if e%2 == remainder[odd_even]:
                            count +=1
                            else:
                            count = 0
                            max_count = max(count, max_count)
                            return max_count


                            To be used in a list comprehension:



                            array = [[1,2,3],[1,2,5,6,8],[2,4,6,9,7],[1,3],[2,4,3,6,8,2]]

                            [max_consecutive(sub, 'even') for sub in array]
                            #=> [1, 2, 3, 0, 3]

                            [max_consecutive(sub, 'odd') for sub in array]
                            #=> [1, 1, 2, 2, 1]






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 4 at 13:11









                            iGianiGian

                            4,9942725




                            4,9942725






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • 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%2fstackoverflow.com%2fquestions%2f54036956%2fcount-of-consecutive-elements-in-a-list-that-satisfy-a-given-condition%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

                                Monofisismo

                                Angular Downloading a file using contenturl with Basic Authentication

                                Olmecas