-1

I'm having problems developing a function to count and return the values of characters in a string. Can't use set, list or dictionaries. Example, the string is AAACCD, should return 3A 2C 1D.

def uniqueValues(string):
count = 0
for s in string:
    if s in "ABCDEFGHIJKL":
        count +=1
return count
print(uniqueValues("AAACCD"))

this will only show the output 6, which is the number of characters of the string.

zeerock
  • 93
  • 1
  • 8
  • 3
    Does this answer your question? [Get the number of occurrences of each character](https://stackoverflow.com/questions/5192753/get-the-number-of-occurrences-of-each-character) – costaparas Feb 19 '21 at 06:02

2 Answers2

0

Something like this? You can use str.count()

def get_counts(s):
    out = ''
    for i in s:
        if i not in out:
            cnt = str(s.count(i))
            out+=(cnt+i+' ')

    return out.strip()

get_counts(s)
'3A 2C 1D'
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0

First take out the unique values from the string and than make a loop of it and count the each characters.

#Python

from itertools import groupby

ab = ''.join(set("AAACCD"))

print(type(ab))

test_str = "AAACCD"

for i in ab:
    
    counter = test_str.count(i)

    print(counter, i)