Home > Back-end >  Count the number of occurrences of characters in a string?
Count the number of occurrences of characters in a string?

Time:10-25

Given a string "a1a3b5a2c4b1". The characters are followed by numbers representing the number of occurrences of the character in the string. The correct solution would return "a6b6c4" (a1 a3 a2 = a6, b5 b1 = b6, c4)

My original idea was to convert the string into a list, then to a dict of key value pairs.

data="a1a3b5a2c4b1"
lst = list(data)
{lst[i]: lst[i  1] for i in range(0, len(lst), 2)}

Returns:

{'a': '2', 'b': '1', 'c': '4'}

The issue is that it does not increase the number of occurrences (values) but takes the last seen value.

How can I create a dictionary that increases the values rather than replaces them?

CodePudding user response:

You keep overriding the key with the latest count in that comprehension. You would have to rather update them by addition:

data = "a1a3b5a2c4b1"

counts = {}
i = iter(data)
for char, count in zip(i, i):
    counts[char] = counts.get(char, 0)   int(count)

# {'a': 6, 'b': 6, 'c': 4}

The other natural util to handle counts is, well, a collections.Counter:

from collections import Counter

counts = Counter()

i = iter(data)
for char, count in zip(i, i):
    counts.update(**{char: int(count)})

This also uses the "zip the same iterator" trick to produce chunks of 2. AS for turning these dictionaries into the desired string output:

"".join(f"{k}{v}" for k, v in counts.items())

CodePudding user response:

If the string is based on sequences of pairs where the first character is your key and the second character is a single digit then:

mystring = 'a1a3b5a2c4b1'
mydict = dict()
for i in range(0, len(mystring), 2):
    pair = mystring[i:i 2]
    key = pair[0]
    value = int(pair[1:])
    if key in mydict:
        mydict[key]  = value
    else:
        mydict[key] = value
print(mydict)

You could play around with defaultdict and/or dictionary comprehension but I think this is clearer

  • Related