Python How to reset counter to 0 inside loop

  • Thread starter Thread starter FallenApple
  • Start date Start date
  • Tags Tags
    Counter Loop
AI Thread Summary
The discussion revolves around a coding challenge that involves counting consecutive ones in a binary list and finding the maximum count of these sequences. The initial code provided fails to reset the count correctly when encountering zeros, leading to incorrect output. It was noted that the loop should check the condition against the elements of the list (A[i] != 0) instead of the list itself. The solution was refined by appending a zero to the end of the list to ensure the last sequence of ones is counted. The final implementation successfully tracks the count of consecutive ones and identifies the maximum count using a single loop. Additionally, participants discussed debugging techniques and the importance of understanding how to traverse the list effectively. The conversation also touched on coding practice resources like LeetCode, which are beneficial for improving coding skills and preparing for technical interviews.
FallenApple
Messages
564
Reaction score
61
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.
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:
Technology news on Phys.org
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
 
@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:
Python:
   (or code=c or code=fortran, whatever)
Your code
 
FallenApple said:
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[i] 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.

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
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.)
Mark44 said:
@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:
Python:
   (or code=c or code=fortran, whatever)
Your code

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.
 
  • Like
Likes FallenApple
wle said:
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
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.


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:
So here is what I ended up with. It turned out to be a problem with the range.
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
 
FallenApple said:
So here is what I ended up with. It turned out to be a problem with the range.

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:
UsableThought said:
Curious how you found the problem?

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. Just wondering if you used a particular trick in this instance.

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.
 
FallenApple said:
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.

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

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:
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
Python:
list(count_consecutive(A))
if you want the list of counts (produces [0, 3, 0, 2, 0, 0, 4] in this case), or
Python:
max(count_consecutives(A))
to find the maximum (4) without constructing the intermediate list.
 
Last edited:
  • Like
Likes FallenApple and UsableThought
  • #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
 

Similar threads

Replies
10
Views
2K
Replies
5
Views
2K
Replies
16
Views
3K
Replies
5
Views
2K
Replies
3
Views
1K
Replies
4
Views
4K
Replies
4
Views
1K
Replies
5
Views
2K
Back
Top