I am using the latest version of python and pycharm professional edition. I am trying to figure out how to take an array like [15, 15, 15, 4, 4, 4, 4, 4, 4] and output [3, 15, 6, 4] where one number represents how many times a value appears in the array and the other number represents what the value was. In the example I provided there are 15 appears 3 times and 4 appears 6 times so the output is [3, 15, 6, 4]. I already have a method that counts the number of unique elements within an array (In the case of this example it would be 2) but I am unsure how I would go about storing both what the value is and how many times it appears. Any help would be appreciated.
How to count number of times a value shows up in an array and what are the different values that show up?
933 Views Asked by Guhan Gnanam At
4
There are 4 best solutions below
0
On
I'm not sure about built in methods but an algorithm to do this would look something like
counts = {}
for i in range(len(my_array)):
if my_array[i] in counts.keys():
counts[my_array[i]] = 1
else:
counts[my_array[i]] += 1
This is a good case for a dictionary. The key would be your number the value would be the count. Scan through your list. You must have that code if you can count how many different numbers are in the list.
Test if the number exists in the dictionary. if yes increment the count. If not store 1 for the new key added.