# Incrementing specified list values, with "catch-up" [closed]

I completed a coding challenge recently in which my function was to be given two parameters: N, the number of counters to be used (numbered 1 through N) - and A, an array of integers. Iterating through the array A, when the index of a counter occurs, that counter is incremented by 1. When an index of N+1 occurs, all of the counters are reset to the maximum counter at that point.

def solution(N, A):
li = [0] * N
#print('A is %s' % A)
#print('N is %s' % N)
max_val = 0

for i in A:
i = i-1
#print('i is %s' % i)
#print('li is %s' % li)
if i == N:
#print('  in if')
li = [max_val] * N
else:
#print('  in else')
li[i] = li[i] + 1
if li[i] > max_val:
max_val = li[i]

return li


[Using Python 3.6]
(See related question.)

• Yes; I missed some code. Updated post. Commented Nov 6, 2018 at 16:12
• Your edit invalidated an answer, which is against the question-and-answer nature of this site. See What should I do when someone answers my question?. Commented Nov 6, 2018 at 16:19
• Having an example would be great I think :) Commented Nov 8, 2018 at 20:46

• li is the name of your list of counters. The fact they are counters matters more than the fact it's a list, so, I'd call it counters.
• I like the clever way you updated all elements in the counters list by creating a new one, but it may be slower than looping through the list and changing all elements in place. It'll also use twice as much memory (before the old one is GC'ed).
• Your previous version didn't update max_val. This was fixed since this was originally posted.
1. I would remove max_val from your code, doing so removes an if-statement as well as a variable.
2. li[i] = li[i] + 1 is the same as li[i] += 1, but I prefer the second (my teacher told me it's faster) and I think it reads nicer, same goes for i = i - 1
3. I agree with the point raised by @rbanffy that li should be called counters.

def solution(N, A):
counters = [0] * N

for i in A:
i -= 1
if i == N:
counters = [max(counters)] * N
else:
counters[i] += 1

return counters


As this is part of coding challenge and not actual code that will be used more regularly I don't think it's an issue that errors, such as one of the inputs being a string, are not taken care of. For the same reason I do not think comments are that important.