Arturo DT
Arturo DT

Reputation: 60

Create function to count occurrence of characters in a string

I want get the occurrence of characters in a string, I got this code:

string = "Foo Fighters"
def conteo(string):
    copia = ''
    for i in string:
        if i not in copia:
            copia = copia + i
    conteo = [0]*len(copia)
    for i in string:
        if i in copia:
            conteo[copia.index(i)] = conteo[copia.index(i)] + 1
    out = ['0']*2*len(copia)
    for i in range(len(copia)):
        out[2*i] = copia[i]
        out[2*i + 1] = conteo[i]
    return (out)

And I want return something like: ['f', 2, 'o', 2, '', 1, 'i', 1, 'g', 1, 'h', 1, 't', 1, 'e', 1, 'r', 1, 's', 1]

How can I do it? Without use a python library

Thank you

Upvotes: 0

Views: 111

Answers (3)

ACascarino
ACascarino

Reputation: 5080

Depending on why you want this information, one method could be to use a Counter:

from collections import Counter
print(Counter("Foo Fighters"))

Of course, to create exactly the same output as requested, use itertools as well:

from collections import Counter
from itertools import chain

c = Counter("Foo Fighters")
output = list(chain.from_iterable(c.items()))

>> ['F', 2, 'o', 2, ' ', 1, 'i', 1, 'g', 1, 'h', 1, 't', 1, 'e', 1, 'r', 1, 's', 1]

Upvotes: 4

jpp
jpp

Reputation: 164613

It's not clear whether you want a critique of your current attempt or a pythonic solution. Below is one way where output is a dictionary.

from collections import Counter

mystr = "Foo Fighters"

c = Counter(mystr)

Result

Counter({' ': 1,
         'F': 2,
         'e': 1,
         'g': 1,
         'h': 1,
         'i': 1,
         'o': 2,
         'r': 1,
         's': 1,
         't': 1})

Output as list

I purposely do not combine the tuples in this list, as it's a good idea to maintain structure until absolutely necessary. It's a trivial task to combine these into one list of strings.

list(c.items())

# [('F', 2),
#  ('o', 2),
#  (' ', 1),
#  ('i', 1),
#  ('g', 1),
#  ('h', 1),
#  ('t', 1),
#  ('e', 1),
#  ('r', 1),
#  ('s', 1)]

Upvotes: 0

Christiaan Vermeulen
Christiaan Vermeulen

Reputation: 41

Use Python Counter (part of standard library):

>>> str = 'foo fighters'
>>> from collections import Counter
>>> counter = Counter(str)
Counter({'f': 2, 'o': 2, ' ': 1, 'e': 1, 'g': 1, 'i': 1, 'h': 1, 's': 1, 'r': 1, 't': 1})
>>> counter['f']
2
>>>

Upvotes: 4

Related Questions