Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Python How to reset counter to 0 inside loop

  1. Jan 29, 2017 #1
    Here is the code. I have binary list of ones and zeros and I want to see the values of the consequtive ones. For example, 111=3 and 11=2

    So I created a count loop and increment the count when A is not 0. Then I tried to update the count to 0 once the for loop got to 0 again, but for some reason, the count doesn't update anymore.

    The output is
    [0, 0, 3, 0] code is in bold.]
    Mod note: Added code tags.
    Code (Python):
    A=[0,1,1,1,0,0,1,1]      #list of binary numbers(0 and 1s)
    count=0                   # count to keep track of a particular grouping of ones.
    countList=[0]        # A list to keep track of all the different counts

    for i in range (0, len(A)-1):
      if A!=0:
        count=count+1
      else:
        countList.append(count)
        count=0                 # resetting the count since i hit value of 0.
    print(countList)
     
    Last edited by a moderator: Jan 29, 2017
  2. jcsd
  3. Jan 29, 2017 #2

    phinds

    User Avatar
    Gold Member
    2016 Award

    But you in effect did NOT reset the count to zero, you reset it to 1. To get it to be 0 again at the top of the loop you have to set it to -1 inside the loop
     
  4. Jan 29, 2017 #3

    Mark44

    Staff: Mentor

    @Fallen Apple, please use code tags, not bold.
    Using code tags preserves the indentation, which is crucial in Python code (which I believe yours to be),

    The tags work like this:
    [code=python] (or code=c or code=fortran, whatever)
    Your code
    [/code]
     
  5. Jan 30, 2017 #4

    wle

    User Avatar

    It's not really well defined what you're trying to do. The way you wrote your loop (assuming you meant A[i] != 0 in the test*), every time it finds a 0 it appends the number of consecutive 1s just before it to countList. It counts the last two 1s just fine (at the end of the loop, count is 2), but doesn't append it to countList because there isn't a 0 at the end of the list A.


    *Since you only use the index i to access elements of A, you could also write the loop as
    Code (Python):
    for x in A:
      if x != 0:
        count += 1
      else:
        countList.append(count)
        count = 0
    (Also you can just write countList = [] at the beginning if you want to start with an empty list.)


    You can also use [PLAIN]...[/PLAIN] to disable BBcode, so you can write e.g. A[PLAIN][i][/PLAIN] to write "A[i]" without the [i] being interpreted as an italics tag.
     
  6. Jan 30, 2017 #5
    Yeah, thanks, those missing 0s are a problem.

    The full problem is below. I'm trying to find the maximum of all the consecutive ones in an array.
    Given a binary array, find the maximum number of consecutive 1s in this array.

    https://leetcode.com/problems/max-consecutive-ones/
     
    Last edited: Jan 30, 2017
  7. Jan 30, 2017 #6
    So here is what I ended up with. It turned out to be a problem with the range.


    Code (Python):
     
    A=[0,1,1,1,0,0,1,1,0,0,0,1,1,1,1] #needs 0 at the end
    A.append(0)
    count=0
    countList=[0]

    for i in range (0, len(A)):
        if A[i]!=0:
            count=count+1
        else:
            countList.append(count)
            count=0

    print(countList)

    Max=countList[0]
    for i in range (1, len(countList)):
      if Max<countList[i]:
        Max=countList[i]
       
       
    print(Max)    




     
    output:


    [0, 0, 3, 0, 2, 0, 0, 4]
    4
     
  8. Jan 30, 2017 #7
    Curious how you found the problem with range?

    I haven't coded in years, but Python used to be my favorite back when I did code; and as I remember, there are lots and lots of techniques for debugging - not just the formal mechanisms built into the language, but informal practices as well. The basic idea is to be able to peek inside execution wherever you like. Just wondering if you used a particular trick in this instance.
     
    Last edited: Jan 30, 2017
  9. Jan 30, 2017 #8
    leetcodes. I've heard they are really good for passing the technical interviews for companies like Google or Facebook. It's also good for improving coding skills in general.

    Well, I was just thinking about how to move through the list and keeping the counts. at first I was thinking about a nested loop, but that overcomplicates things. So then I thought of totaling up the ones and then getting it to stop once it reaches a 0. The tricky part is to set the counter to 0 so I can redo the counting on the next set of 1's within the same for loop.
     
  10. Jan 30, 2017 #9

    wle

    User Avatar

    You can count the consecutive ones and find the maximum in just one loop. (Also, Python has a built-in function max() which can find the maximum element in a list.)

    Code (Python):
    def max_consecutive_ones(lst):
      count = 0
      max_count = 0

      for x in lst:
        if x == 1:
          count += 1

          if count > max_count:
            max_count = count
        else:
          count = 0

      return max_count
    then do print(max_consecutive_ones(A)).

    If you know more about Python you can do more sophisticated things, e.g. using a generator you can defer deciding if you need the list of counts or if you just want the maximum count without constructing the whole list of counts:
    Code (Python):
    def count_consecutive(lst, test_function=lambda x: x == 1):
      count = 0

      for x in lst:
        if test_function(x):
          count += 1
        else:
          yield count
          count = 0

      yield count
    then you can do
    Code (Python):
    list(count_consecutive(A))
    if you want the list of counts (produces [0, 3, 0, 2, 0, 0, 4] in this case), or
    Code (Python):
    max(count_consecutives(A))
    to find the maximum (4) without constructing the intermediate list.
     
    Last edited: Jan 30, 2017
  11. Feb 8, 2017 #10
    Is your array input made up of groups of 4 bits? If so could you grab the bits out of the array as a nibble which are short int's and do direct comparison of nibbles (BCD numbers) to determine which number contains the most number of 1's in a sequence
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: How to reset counter to 0 inside loop
  1. How to Loop this C++ (Replies: 2)

  2. Learning programming (Replies: 4)

Loading...