0

I am trying to find the number of duplicate (repeated) digits in a number, for each unique digit. eg. For 21311243 there would be 3 1's and 2 2's and 2 3's, so I would just need [3,2,2] where order doesn't matter. I am trying to do this as follows, where number_list = ['2','1','3','1','1','2','4', '3']. The code below works for the above number and I get that repeated_numbers = [2, 2, 3] as expected. However, for 213112433 repeated_numbers = [2, 3, 3, 2] for some reason and I don't know why this is and how to rectify the code below as such:

repeated_numbers = [] #The number of repeated digits for each unique digit
for a in number_list:
        i = 0
        for b in number_list:
            if (a == b):
                i = i + 1

        if i > 1: #If the particular digit is repeated
            repeated_numbers.append(i) 
            number_list.remove(a) #Get rid of the digit that gets repeated from the list

Also, I am open to better ways of doing this as my way has O(n^2) complexity, but need that number_list is considered as a list of characters.

user131983
  • 3,787
  • 4
  • 27
  • 42
  • `[s for s,v in collections.Counter(numberlist).items() if v > 1]` – Joran Beasley Sep 28 '15 at 23:28
  • 2
    This is supported in the [collections module](https://docs.python.org/2/library/collections.html) . . . Check out the highest voted answer to http://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python – ernie Sep 28 '15 at 23:29

1 Answers1

0

Removing elements in a list while iterating on it is not a good idea. Look at this related question: Remove items from a list while iterating

I suggest using list comprehension to solve your problem.

As far as the specific bug in your program, I think you meant to remove all occurences of a specific number when performing remove but that's not what happens:

Look at: https://docs.python.org/2/tutorial/datastructures.html

list.remove(x)

Remove the first item from the list whose value is x. It is an error if there is no such item.

Community
  • 1
  • 1
igon
  • 3,016
  • 1
  • 22
  • 37