Search code examples
pythonarrayslistflagsdigits

How to create an array of 10 digits for counting repetitions?


I wondered how to create an array of 10 digits, such that each time a digit of a number shows, it increments its matching place in the 10 digits array, like this:

digits=[0,0,0,0,0,0,0,0,0,0]
num_digits=[1,2,3,9,1]

and digits becomes:

digits=[0,2,1,1,0,0,0,0,0,1]

I tried:

digits[num_digits[j]]=digits[num_digits[j]]+1

(j goes backwards on num_digits elements) but I got the error "list indices must be integers, not list".

Thanks in advance!


Solution

  • >>> digits=[0,0,0,0,0,0,0,0,0,0]
    >>> num_digits=[1,2,3,9,1]
    >>> for d in num_digits:
    ...     digits[d] += 1
    ... 
    >>> digits
    [0, 2, 1, 1, 0, 0, 0, 0, 0, 1]
    

    We wouldn't need a variable j for a simple iteration of a list.